码迷,mamicode.com
首页 > 其他好文 > 详细

Balanced Binary Tree Leetcode

时间:2017-06-12 00:40:11      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:for   ever   problem   height   复杂度   bin   fine   boolean   方法   

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;
    }
}

 

Balanced Binary Tree Leetcode

标签:for   ever   problem   height   复杂度   bin   fine   boolean   方法   

原文地址:http://www.cnblogs.com/aprilyang/p/6986892.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!