标签:
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 a binary tree node.
* 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) {
bool leftsame = 0;
bool rightsame = 0;
if((p==NULL)&&(q==NULL))return true;
else if((p==NULL)&&(q!=NULL))return false;
else if((p!=NULL)&&(q==NULL))return false;
if(p->val != q->val)return false;
leftsame = isSameTree(p->left,q->left);
rightsame = isSameTree(p->right,q->right);
return (leftsame&&rightsame);
}
};/**
* Definition for a binary tree node.
* 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) {
stack<TreeNode*> s1;
stack<TreeNode*> s2;
if(p==NULL&&q==NULL)
return true;
else if(p!=NULL&&q!=NULL)
{
s1.push(p);
s2.push(q);
}
else
return false;
while(!s1.empty()&&!s2.empty())
{
TreeNode* t1=s1.top();
TreeNode* t2=s2.top();
if(t1->val!=t2->val)
return false;
s1.pop();
s2.pop();
if(t1->left&&t2->left)
{
s1.push(t1->left);
s2.push(t2->left);
}
else if((t1->left==NULL^t2->left==NULL)==1)
return false;
if(t1->right&&t2->right)
{
s1.push(t1->right);
s2.push(t2->right);
}
else if((t1->right==NULL^t2->right==NULL)==1)
return false;
}
if(s1.empty()&&s2.empty())
return true;
return false;
}
};标签:
原文地址:http://blog.csdn.net/u011391629/article/details/52247565