# 100. Same Tree

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) {
queue<TreeNode*> pque,qque;
if (p&&q)
{
pque.push(p);
qque.push(q);
}
else if (!p&&!q)  return true;
else return false;
while (!pque.empty()&&!qque.empty())
{
if (pque.front()->val!=qque.front()->val)
return false;
else
{
TreeNode* pp=pque.front(),*qq=qque.front();
pque.pop();
qque.pop();
if (pp->left&&qq->left)
{
pque.push(pp->left);
qque.push(qq->left);
}
else if(!pp->left&&!qq->left) {}
else return false;
if (pp->right&&qq->right)
{
pque.push(pp->right);
qque.push(qq->right);
}
else if(!pp->right&&!qq->right) {}
else return false;
}
}
if (!pque.empty()||!qque.empty())
return false;
return true;
}
};

/**
* 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) {
if(!p && !q)
return true;
else if(!p && q)
return false;
else if(p && !q)
return false;
else
{
if(p->val != q->val)
return false;
else
return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
}
};


• 本文已收录于以下专栏：

举报原因： 您举报文章：100. Same Tree 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)