题解 | #判断二叉树是否相等#
判断二叉树是否相等
http://www.nowcoder.com/practice/9a9e74b71f944efab9992925f7f9a65e
2. 判断二叉树是否相等
解题思路:用栈(stack)模拟实现
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param p TreeNode类
* @param q TreeNode类
* @return bool布尔型
*/
bool isSameTree(TreeNode* p, TreeNode* q) {
// write code here
if (p == nullptr || q == nullptr)
{
return p == q;
}
stack<TreeNode*> st1, st2;
st1.push(p);
st2.push(q);
while (!st1.empty() && !st2.empty())
{
TreeNode* a = st1.top();
TreeNode* b = st2.top();
st1.pop();
st2.pop();
if (a->val != b->val)
{
return false;
}
if (a->left && b->left)
{
st1.push(a->left);
st2.push(b->left);
}
else if (a->left || b->left)
{
return false;
}
if (b->right && b->right)
{
st1.push(a->right);
st2.push(b->right);
}
else if (b->right || b->right)
{
return false;
}
}
if (st1.empty() && st2.empty())
{
return true;
}
else
{
return true;
}
}
};