【两次过】Lintcode 93. 平衡二叉树

本文介绍了一种算法,用于判断给定的二叉树是否为高度平衡的二叉树。通过递归地计算每个节点的左右子树的最大深度,并比较它们之间的差值来实现。提供了两种解题思路及相应的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。 

样例

给出二叉树 A={3,9,20,#,#,15,7}, B={3,#,20,15,7}

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

二叉树A是高度平衡的二叉树,但是B不是

解题思路1:

    由于需要每个子树的深度信息,所以需要增加一个最大深度函数,用来返回当前节点的最大深度,这个深度函数类似于Lintcode 97:二叉树的最大深度。然后再用高度差信息判断当前节点是否为平衡节点,是则继续向下判断,否则返回false.

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

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) {
        // write your code here
        if(root == null)
            return true;
        
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        
        if(Math.abs(leftDepth-rightDepth) > 1)
            return false;
        else
            return isBalanced(root.left) && isBalanced(root.right);
    }
    
    private int maxDepth(TreeNode root){
        if(root == null)
            return 0;
        
        int leftDepth = maxDepth(root.left);
        int rightDepth = maxDepth(root.right);
        
        return Math.max(leftDepth, rightDepth) + 1;
    }
}

解题思路2:

利用全局变量保存结果,其余与上相同。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

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) {
        // write your code here
        maxLength(root);
        
        return res;
    }
    
    private boolean res = true;
    
    public int maxLength(TreeNode root){
        if(root == null)
            return 0;
        
        int l = maxLength(root.left);
        int r = maxLength(root.right);
        
        if(Math.abs(l - r) > 1)
            res = false;
        
        return Math.max(l, r) + 1;
            
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值