LeetCode#110: Balanced Binary Tree

Description

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.

Example

Given the following tree [3,9,20,null,null,15,7]:

    3
   / \
  9  20
    /  \
   15   7
   
Return true.
Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
      / \
     2   2
    / \
   3   3
  / \
 4   4
 
Return false.

Solution

要判断一棵二叉树是否平衡,先判断左右子树的高度差是否超过1,再递归地判断左右子树是否平衡。因此可以很容易地想到最直观的做法:

public class Solution2 {
    public boolean isBalanced(TreeNode root) {
    	if(root == null)
    		return true;
        int left = depth(root.left);
        int right = depth(root.right);
        return Math.abs(left-right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }
    
    private int depth(TreeNode node) {
    	if(node == null)
    		return 0;
    	return Math.max(depth(node.left), depth(node.right)) + 1;
    }
}

由于depth()方法要遍历该树的所有节点,时间复杂度为O(n),而判断每个子树是否平衡都需要使用它来得到其子树的深度,因此总共的时间复杂度为O(n^2)。可以看出,由于depth()的重复使用导致该算法做了许多没必要的操作。

如果把上面这种解法理解成由上至下重复的计算深度并判断是否平衡,那么以下的解法则是由下至上的逐步计算高度并判断是否平衡:

public class Solution {
    public boolean isBalanced(TreeNode root) {
        return height(root) != -1;
    }
    
    private int height(TreeNode node) {
    	if(node == null)
    		return 0;
    	int left = height(node.left);
    	if(left == -1) return -1;
    	int right = height(node.right);
    	if(right == -1) return -1;
    	
    	if(Math.abs(left - right) > 1) return -1;
    	return Math.max(left, right) + 1;
    }
}

这种解法无需重复的计算每个子树的深度,而是由下至上的一步步构建完成,在构建的过程中如果发现不满足平衡条件也就是左右子树的高度差大于1了就直接返回-1,否则就返回当前的高度。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值