[Lintcode] Balanced Binary Tree

平衡二叉树判定
本文介绍了一种通过递归计算二叉树的最大深度来判断其是否为平衡二叉树的方法。平衡二叉树定义为任意节点的两棵子树深度之差不超过1。文中详细解释了递归函数的设计思路与实现细节。
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.

Example

Given binary tree A={3,9,20,#,#,15,7}, B={3,#,20,15,7}

A)  3            B)    3 
   / \                  \
  9  20                 20
    /  \                / \
   15   7              15  7

The binary tree A is a height-balanced binary tree, but B is not.

SOLUTION :

二叉树的问题,必须是分治大法好!

首先分析,这个题最终返回的是boolean值,但是中间要用到深度,是int值,所以要做一个递归函数方便统计最大深度,这个递归函数需要传入root,返回的是int值最大深度。

分左右两边去递归求两边最大深度,但是这个题是看这个树是不是平衡,所以中间只要出现不平衡那么整个树就不平衡,所以中间要加一些中止判断条件。

考虑中止判断条件时候考虑,一共有三种情况会导致整个树不平衡:1,左子树不平衡。2,右子树不平衡。3,左右子树平衡,但是高度差大于1.

于是开始写代码:

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: True if this Binary tree is Balanced, or false.
     */
    public boolean isBalanced(TreeNode root) {
        if (root == null){
            return true;
        }
        return maxDepth(root) != -1;
    }
    private int maxDepth(TreeNode root){
        if (root == null){
            return 0;
        }
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        // 用-1代表不平衡
        if (left == -1 || right == -1 || Math.abs(left - right) > 1){
            return -1;
        }
        // 求左右子树最大深度
        return Math.max(left, right) + 1;
    }
}

  

 

转载于:https://www.cnblogs.com/tritritri/p/4856949.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值