首页 > 其他 > 详细

平衡二叉树

时间:2020-02-25 16:31:19      阅读:46      评论:0      收藏:0      [点我收藏+]

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

思路

深度搜索,剪枝。
时间复杂度O(lgn),空间复杂度O(lgn)。

未剪枝代码

public class Solution {
    private int depth(TreeNode root) {
        return root == null ? 0 : Math.max(1+depth(root.left), 1+depth(root.right));
    }
    
    public boolean IsBalanced_Solution(TreeNode root) {
        return root == null ? true : Math.abs(depth(root.left) - depth(root.right)) <= 1;
    }
}

剪枝代码

public class Solution {
    private int depth(TreeNode root) {
        if(root == null)    return 0;
        int left = depth(root.left);
        if(left == -1){
            return -1;
        }
        int right = depth(root.right);
        if(right == -1) {
            return -1;
        }
        return Math.abs(left-right) < 2 ? 1 + Math.max(left, right) : -1;
    }
    
    public boolean IsBalanced_Solution(TreeNode root) {
        return depth(root) != -1;
    }
}

平衡二叉树

原文:https://www.cnblogs.com/ustca/p/12362184.html

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