题解 | #平衡二叉树#
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); } }
```