Balanced Binary Tree Leetcode

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

 

这道题一开始的做法比较简单粗暴。
public class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        boolean left = isBalanced(root.left);
        boolean right = isBalanced(root.right);
        int l = depth(root.left);
        int r = depth(root.right);
        return Math.abs(l - r) <= 1 && left && right;
    }
    public int depth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = depth(root.left);
        int right = depth(root.right);
        return Math.max(left, right) + 1;
    }
}

这样的话,每个节点都要求一次depth,depth的时间复杂度是O(n),所以总共的时间复杂度是O(n^2)。

可以采取自下而上(bottom up)的方法。这样的话,时间复杂度是O(n)。需要注意的是,只要左右有一个是-1,可以直接返回-1。不然的话可能出现两个子树的深度相同,但他们并不是平衡的。

public class Solution {
    public boolean isBalanced(TreeNode root) {
        return depthDif(root) != -1;
    }
    public int depthDif(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = depthDif(root.left);
        if (left == -1) {
            return -1;
        }
        int right = depthDif(root.right);
        if (right == -1) {
            return -1;
        }
        return Math.abs(left - right) <= 1 ? Math.max(left, right) + 1 : -1;
    }
}

 

posted @ 2017-06-11 23:30  璨璨要好好学习  阅读(119)  评论(0编辑  收藏  举报