Given two binary trees, write a function to check if they are equal or not. //判断二叉树的相等
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
#include <iostream>
#include <stdlib.h>
using namespace std;
/**
* Definition for binary tree
*/
struct TreeNode {
char val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//前序法创建二叉树
void CreateBiTree(TreeNode* &T,char* &str) {
if(*str++=='#')
T=NULL;
else {
T=(TreeNode*)malloc(sizeof(TreeNode));
if(!T) exit(1);
T->val=*(str-1);
CreateBiTree(T->left,str); //构造左子树
CreateBiTree(T->right,str); //构造右子树
}
}
bool isSameTree(TreeNode *p, TreeNode *q) {
if(p==NULL && q==NULL)
return true;
else if(p!=NULL && q!=NULL) {
//递归判断求解
return ((p->val==q->val)&& isSameTree(p->left,q->left) && isSameTree(p->right,q->right));
}
else
return false;
}
int main()
{
TreeNode *T1,*T2;
char* ch;
char case1[]={"ABC##DE#G##F###"}; //用于创建二叉树的字符数组
char case2[]={"ABC##DE#G##F###"};
ch=case1;
CreateBiTree(T1,ch);
ch=case2;
CreateBiTree(T2,ch);
cout << isSameTree(T1,T2) << endl;
return 0;
}