110. Balanced Binary Tree

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.

 

可以先求出每个subtree的深度,然后比较。但不高效,时间复杂度为O(nlgn).因为每一次计算左右subtree深度为2*O(lgn), 然后递归n次。

public bool IsBalanced(TreeNode root) {
        if(root == null) return true;
        int left =  TreeHeight(root.left);
        int right = TreeHeight(root.right);
        if ((left>=right+2)||(left+2<=right)) return false;
        return IsBalanced(root.left)&& IsBalanced(root.right);
    }
    
    public int TreeHeight(TreeNode root)
    {
        if(root == null) return 0;
        if(root.left == null && root.right == null) return 1;
        return Math.Max(TreeHeight(root.left), TreeHeight(root.right))+1;
    }

 

优化的方法为DFS,先check更小的subtree是否为Balanced Tree, 如果不是则直接返回false。参考http://www.cnblogs.com/grandyang/p/4045660.html

 

 public bool IsBalanced(TreeNode root) {
        return !(TreeHeight(root)==-1);
    }
    
    public int TreeHeight(TreeNode root)
    {
        if(root == null) return 0;
        int left = TreeHeight(root.left);
        if(left == -1) return -1;
        int right = TreeHeight(root.right);
        if(right == -1) return -1;
        if ((left>=right+2)||(left+2<=right)) return -1;
        return Math.Max(left, right)+1;
    }

 

posted @ 2016-09-11 23:08  咖啡中不塌缩的方糖  阅读(176)  评论(0编辑  收藏  举报