等价二叉树

来源:互联网 发布:淘宝促销短信模板 编辑:程序博客网 时间:2024/06/05 11:34
题目描述:

检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,并且每个对应位置上的节点上的数都相等。

样例
    1             1   / \           / \  2   2   and   2   2 /             /4             4

就是两棵等价的二叉树。

    1             1   / \           / \  2   3   and   2   3 /               \4                 4

就不是等价的。

解题思路:判断两棵树的节点是否为空,若两节点都为空,返回true;如果其中一个节点为空,另外一个节点不为空,则返回false;若两节点都不为空,则要判断左子树等于左子树,右子树等于右子树,则两棵二叉树等价。

代码实现:

class Solution {
public:
    /**
     * @aaram a, b, the root of binary trees.
     * @return true if they are identical, or false.
     */
    bool isIdentical(TreeNode* a, TreeNode* b) {
        // Write your code here
        if(a==NULL&&b==NULL)
        return true;
        if(a==NULL||b==NULL)
        return false;
        if(a->val==b->val)
        return isIdentical(a->left,b->left)&&isIdentical(a->right,b->right);
        else return false;
    }
};

感想:要考虑到判断二叉树的每一种情况,判断两棵树同一节点的左子树和右子树是否相同,若相同,则二叉树等价,否则二叉树不等价。


0 0
原创粉丝点击