题解 | #平衡二叉树#

import java.util.*;
import java.util.Map;
public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        highmap.put(null,0);
        depth(root);
        return judgehighabs(root);
    }    
    Map<TreeNode,Integer> highmap=new HashMap<TreeNode,Integer>();
//求树的高度
    int depth(TreeNode root){
        if (root==null){
            return 0;            
        }
        if(highmap.containsKey(root)){
            return highmap.get(root);
        }
        int leftvalue=depth(root.left);
        int rightvalue=depth(root.right);
        highmap.put(root,Math.max(leftvalue,rightvalue)+1);
        return highmap.get(root);
    }

//判断树的作业平衡

    private boolean judgehighabs(TreeNode root){
        if(root==null){
            return true;
        }
       return (Math.abs(highmap.get(root.left)-highmap.get(root.right))<2)
                     &&judgehighabs(root.left)&&judgehighabs(root.right);

    }
}

```

全部评论

相关推荐

仁者伍敌:牛子这些人还会点一个自动回复,boss都不带回复的
点赞 评论 收藏
分享
醉蟀:你不干有的是人干
点赞 评论 收藏
分享
07-01 17:14
中北大学 Java
兄弟们是真是假
牛客46374834...:我在boss上投java岗从来没成功过
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务