469.等价二叉树

来源:互联网 发布:java jdbc mysql 编辑:程序博客网 时间:2024/06/05 04:18

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


样例:

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

就是两棵等价的二叉树。

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

就不是等价的。


代码:

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)||(a==NULL&&b!=NULL))           return false;        if(a->val==b->val)       {             if(isIdentical(a->left,b->left)&&isIdentical(b->right,a->right))        return true;       }      else          return false;    }};

感想:在两棵树a,b中,如果两树都为空,即等价;两树中一空一不为空,不等价。除去这两种情况,从根开始,比较两树中的值是否相等,然后再利用递归的思想,比较左右子树,判断是否等价。

0 0