输入 A
B C
D E F G
H I J
以先序遍历,用“#”表示为空,输入ABDH##I##EJ###CF##G##
再输入一棵二叉树,进行判断
#include <iostream>
#include <stack>
#include <queue>
using namespace std;
typedef char Elementtype;
typedef struct node
{
struct node *lchild;
struct node *rchild;
Elementtype data;
}BiTreeNode, *BTREE;
void CreateBTree(BTREE &T) //先序顺序建立二叉树
{
char c;
cin >> c;
if('#' == c)
T = NULL;
else
{
T = new node;
T->data = c;
CreateBTree(T->lchild); //递归建立
CreateBTree(T->rchild);
}
}
int IsEmpty(BTREE root)
{
if (root == NULL)
return 1;
else
return 0;
}
bool Equal(BTREE firstbt,BTREE secondbt)//判断两棵二叉树是否等价
{
bool x;
x = false;
if((IsEmpty(firstbt))&&(IsEmpty(secondbt)))
x = true;
else if(!IsEmpty(firstbt)&&!IsEmpty(secondbt))
if((firstbt->data)==(secondbt->data))
if(Equal(firstbt->lchild,secondbt->lchild))
x = Equal(firstbt->rchild,secondbt->rchild);
return x;
}
BTREE CopyBT(BTREE oldtree)
{
BTREE temp;
if(oldtree==NULL)
return NULL;
else
{
temp = new node;
temp->data = oldtree->data;
temp->lchild = CopyBT(oldtree->lchild);
temp->rchild = CopyBT(oldtree->rchild);
return temp;
}
}
int main()
{
BTREE T1,T2;
BTREE T3;
CreateBTree(T1);
CreateBTree(T2);
if(Equal(T1,T2))
cout << "Right!" << endl;
else
cout << "No!" << endl;
T3 = CopyBT(T2);
if(Equal(T1,T3))
cout << "Right!" << endl;
else
cout << "No!" << endl;
return 0;
}