《程序员面试金典》

6 篇文章 0 订阅

4.1 检查二叉树是否平衡

代码实现
// 获取二叉树的树高度,判断二叉树是否平衡
class TreeNode {
    public int val = 0;
    public TreeNode left = null;
    public TreeNode right = null;
}

public class Solution {
    // 获取树高度,用递归的方法:左、右子树的最大高度加一
    public static int getHeight(TreeNode node) {
        if (node == null) // 递归结束条件
            return 0;
        else // 左右子树的最大高度加一
            return Math.max(getHeight(node.left), getHeight(node.right))+1;
    }

    // 递归判断树是否平衡:先判断当前节点是否平衡,平衡时再判断左右子树是否平衡
    public static boolean isBalance(TreeNode node) {
        if (node == null) // 递归结束条件
            return true;

        // 获取左右子树高度,判断当前节点是否平衡
        int left = getHeight(node.left);
        int right = getHeight(node.right);

        if (Math.abs(left - right) > 1) // 递归结束条件
            return false;
        else
            return isBalance(node.left) && isBalance(node.right);
    }

    // 改进方法,从根节点递归向下检查每棵子树的高度
    public static boolean isBalance2(TreeNode root) {
        if (checkHeight(root) == -1)
            return false;
        else
            return true;
    }

    public static int checkHeight(TreeNode node) {
        if (node == null)
            return 0;

        // 获取左子树高度,并判断是否平衡
        int leftHeight = checkHeight(node.left);
        if (leftHeight  == -1)
            return -1;

        // 获取右子树高度,并判断是否平衡
        int rightHeight = checkHeight(node.right);
        if (leftHeight  == -1)
            return -1;

        // 检查当前节点是否平衡
        if (Math.abs(leftHeight - rightHeight) > 1)
            return -1;
        else
            return Math.max(checkHeight(node.left), checkHeight(node.right)) + 1;

    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值