算法思路:
其实思路不难,递归判断左节点的左孩子是否等于右节点的右孩子,并且左节点的右孩子等于右节点的左孩子
#include <iostream>
using namespace std;
struct BinNode
{
char data;
BinNode *lchild;
BinNode *rchild;
};
void Create(BinNode* &root)
{
char ch;
cin >> ch;
if(ch == '#')
{
root = NULL;
}
else
{
root = new BinNode;
root->data = ch;
Create(root->lchild);
Create(root->rchild);
}
}
int JudgeTree(BinNode *p, BinNode *q)
{
if(p==NULL && q==NULL)
{
return 1;
}
else if(p->data==q->data && p!=NULL && q!=NULL) //左子树的左孩子等于右子树的右孩子,左子树的右孩子等于右子树的左孩子
{
JudgeTree(p->lchild, q->rchild);
JudgeTree(p->rchild, q->lchild);
}
else
{
return 0;
}
}
void PreOrder(BinNode *root)
{
if(root == NULL)
{
return;
}
else
{
cout <<root->data;
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void Release(BinNode *root)
{
if(root == NULL)
{
return;
}
else
{
Release(root->lchild);
Release(root->rchild);
delete root;
}
}
int main()
{
int flag = 0;
BinNode *root = NULL;
Create(root);
PreOrder(root);
if(root != NULL)
{
flag = JudgeTree(root->lchild, root->rchild);
}
cout <<'\n'<< flag << '\n';
Release(root);
return 0;
}