#include <iostream>
#include<cstdlib>
#include<stdio.h>
using namespace std;
typedef struct bTree{
char data;
struct bTree *lch,*rch;
}bTree;
bTree* creat(bTree *p){
char c;
scanf("%c",&c);
if(c == ' ')
p = NULL;
else{
p = (bTree*)malloc(sizeof(bTree));
p->data = c;
p->lch = creat(p->lch);
p->rch = creat(p->rch);
}
return p;
}
//中序輸出
void printMid(bTree* p){
if (p){
printMid(p->lch);
cout<<p->data;
printMid(p->rch);
}
}
//判斷二叉樹T1,T2是否相似,是回傳true,否回傳false
bool SimilarTree(bTree *T1,bTree *T2){
if(!T1){// T1是空樹
if(!T2)
return true;// T2是空樹
else
return false;
}
else{// T1是非空樹
if(!T2) return false;
else{// T2是非空樹
if(SimilarTree(T1->lch,T2->lch)&&SimilarTree(T1->rch,T2->rch))
return true;
else
return false;
}
}
}
int main(){
bTree *B1 = NULL, *B2 = NULL;
cout<<"構建二叉樹B1:"<<endl;
B1 = creat(B1);
cout<<"構建二叉樹B2:"<<endl;
B2 = creat(B2);
cout<<"請確定你的輸入資訊:"<<endl;
cout<<"B1中序遍歷:";
printMid(B1);
cout<<endl<<"B2中序遍歷:";
printMid(B2);
cout<<end;
if(SimilarTree(B1,B2))
cout<<"B1,B2是相似二叉樹"<<endl;
else
cout<<"B1,B2不是相似二叉樹"<<endl;
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/100293.html
標籤:基礎類
