题解 | #平衡二叉树#

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);

    }
}

```

全部评论

相关推荐

自由水:笑死了,敢这么面试不敢让别人说
点赞 评论 收藏
分享
06-25 16:53
门头沟学院 Java
人力小鱼姐:简历可以直接用飞书模板 模拟面试可以试试ai,现在好多都还是免费阶段 像Sugar云面、多面鹅都不错,主要看面试后自己能不能复盘出有效信息
为了找工作你花了哪些钱?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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