题解 | #平衡二叉树#

平衡二叉树

http://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222

java版平衡树,是每个节点的左子树和右子树深度不超过1,所以需要遍历每个节点,并且得到左右子树的深度

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root == null) return true;
        //每个节点的左子树深度
        int l = dfs(root.left);
        //每个节点的右子树深度
        int r = dfs(root.right);
        return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right) && Math.abs(l - r) <= 1; 
    }
    public int dfs(TreeNode t){
        if(t == null){
            return 0;
        }
        return Math.max(dfs(t.left),dfs(t.right)) + 1;
    }
}
全部评论

相关推荐

工科女的日常:真诚建议:别再用这种花哨的模板,可以看看我发的那个零经验找实习发帖子
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务