标签:
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.
这道题是要判断两棵树是不是全等。全等的定义是:
不仅树的结构要完全相同,相同位置上的结点的值也要相同。
思路很容易想到,对二叉树的层次遍历做一点修改:
取队列结点,将它的左右孩子指针全部入队列,无论存在不存在。
下面贴上代码:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode *p, TreeNode *q) {
queue<TreeNode*> p1;
queue<TreeNode*> p2;
p1.push(p);
p2.push(q);
TreeNode* t1;
TreeNode* t2;
while (!p1.empty()&&!p2.empty()){
t1 = p1.front();
t2 = p2.front();
if (t1&&t2){
if (t1->val != t2->val)
return false;
}
else if((t1&&!t2)||(!t1&&t2)){
return false;
}
else{
p1.pop();
p2.pop();
continue;
}
p1.pop();
p2.pop();
p1.push(t1->left);
p1.push(t1->right);
p2.push(t2->left);
p2.push(t2->right);
}
if (p1.empty() && p2.empty())
return true;
else
return false;
}
};
标签:
原文地址:http://blog.csdn.net/kaitankedemao/article/details/44342423