首页 > 其他 > 详细

平衡二叉树

时间:2020-04-11 21:43:52      阅读:85      评论:0      收藏:0      [点我收藏+]

解题思路:先计算左右子树的高度,如果满足平衡二叉树左右子树的高度差的绝对值不超过1,则返回该树的高度,否则返回-1表示子树已经不平衡了.

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:

一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]


    3
   /   9  20
    /     15   7

返回 true 。
class Solution {
    public static int height(TreeNode root){
        if(root == null){
            return 0;
        }
        int leftHight = height(root.left);
        int rightHeight = height(root.right);
        if(leftHight >= 0 && rightHeight >=0 && Math.abs(leftHight-rightHeight) <=1){
            return Math.max(leftHight,rightHeight)+1;
        }else{
            return -1;
        }
    }
    public boolean isBalanced(TreeNode root) {
        return height(root) >= 0;
    }
}

平衡二叉树

原文:https://blog.51cto.com/14472348/2486588

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!