题目:
检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,并且每个对应位置上的节点上的数都相等。
样例
1 1
/ \ / \
2 2 and 2 2
/ /
4 4
就是两棵等价的二叉树。
1 1
/ \ / \
2 3 and 2 3
/ \
4 4
就不是等价的。
思路:
此题与遍历的思想一致。同时遍历两棵树,并互相比较两棵树的结点,看是否一致,若一致,则继续遍历,知道遍历结束,输出1;若遍历过程中遇到结点不相同,则两颗树不等价,遍历结束,输出0.
具体代码:
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @aaram a, b, the root of binary trees.
* @return true if they are identical, or false.
*/
bool isIdentical(TreeNode* a, TreeNode* b) {
// Write your code here
int top=-1;
int c;
TreeNode* aa[100000];
TreeNode* bb[100000];
while((a!=NULL&&b!=NULL)||top!=-1){
while(a!=NULL&&b!=NULL&&a->val==b->val){
top++;
c=top;
aa[c]=a;
bb[c]=b;
a=a->left;
b=b->left;
}
if(a!=NULL||b!=NULL) return 0;
else if(top!=-1){
a=aa[c];
b=bb[c];
top--;
c=top;
b=b->right;
a=a->right;
}
}
if(a==NULL&&b==NULL)return 1;
else return 0;
}
};
感悟:
此题与遍历树一致,只不过是同时遍历两棵树并比较结点。自己对于递归的思想还是没有领悟到位,所以采用了非递归的方法。