LintCode - 等價二叉樹(普通)

weixin_34107955發表於2016-11-27

版權宣告:本文為博主原創文章,未經博主允許不得轉載。

難度:容易
要求:

檢查兩棵二叉樹是否等價。等價的意思是說,首先兩棵二叉樹必須擁有相同的結構,並且每個對應位置上的節點上的數都相等。

樣例

    1             1
   / \           / \
  2   2   and   2   2
 /             /
4             4
就是兩棵等價的二叉樹。

    1             1
   / \           / \
  2   3   and   2   3
 /               \
4                 4
就不是等價的。

思路

/**
     * @param a, b, the root of binary trees.
     * @return true if they are identical, or false.
     */
    public boolean 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) || a.val != b.val) {
            return false;
        }

        boolean left = isIdentical(a.left, b.left);
        boolean right = isIdentical(a.right, b.right);
        return left && right;
    }

相關文章