Balanced binary tree

不能只用分治法看看左邊是不是平衡或是只看右邊,

因為這樣會讓 [1, 2, 3, 4, 5] 過不了

應該要用個 ResultType 來將左右樹的最高高度記下來

class Result {
    boolean isBalanced;
    int depth;
    public Result(boolean b, int d) {
        isBalanced = b;
        depth = d;
    }
}

public boolean isBalanced(TreeNode root) {
    // write your code here
    if (root == null) {
        return true;
    }

    return helper(root).isBalanced;
}

public Result helper(TreeNode root) {
    if (root == null) {
        return new Result(true, 0);
    }

    Result left = helper(root.left);
    Result right = helper(root.right);

    if (!left.isBalanced) {    //if it's not balanced, not need to go on
        return left;
    }
    if (!right.isBalanced) {
        return right;
    }

    if (Math.abs(left.depth - right.depth) > 1) {
        return new Result(false, Math.max(left.depth, right.depth) + 1);
    }
    else {
        return new Result(true, Math.max(left.depth, right.depth) + 1);
    }

}

results matching ""

    No results matching ""