目录
原题描述
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.
分析
提供两棵树的根节点,比较两棵树是否相等,即要求结构相同且对应节点值相等。这题与求树的最大深度类似,利用递归将树不断分解转化为单个节点的比较。对于一个节点来说,有3种情况:空节点,非叶子结点,叶子节点。
现在有两棵树,组合起来则是9种情况。经过分析,可将这9种情况实际分成4种:
1.两节点中存在空节点,此时只有两个节点都为空节点时才是相等的
2.两节点都是非叶子结点,此时只有两节点的值相等且对应子树相等时才是相等的
3.两节点都是叶子节点,此时只要两节点值相等就是相等的
4.其他情况都不相等
代码示例
/**
* 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 isParent(TreeNode* p)
{
if (p == NULL)
return false;
else
return p->left != NULL || p->right != NULL;
}
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p == NULL || q == NULL)
return p == NULL && q == NULL;
else if (isParent(p) && isParent(q))
return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
else if (!isParent(p) && !isParent(q))
return p->val == q->val;
else
return false;
}
};