题解 | #判断二叉树是否相等#
判断二叉树是否相等
http://www.nowcoder.com/practice/9a9e74b71f944efab9992925f7f9a65e
2. 判断二叉树是否相等
解题思路:递归
/**
* 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;
}
if (p->val != q->val)
{
return false;
}
bool left = isSameTree(p->left, q->left);
bool right = isSameTree(p->right, q->right);
return left && right;
}
};