# 剑指offer-39：平衡二叉树

## 解题思路

 1 private HashMap<TreeNode, Integer> nodeDepth = new HashMap<>();
2 private boolean flag = true;
3
4 public boolean IsBalanced_Solution(TreeNode root) {
5     if (root == null) {
6         return true;
7     }
8     if (flag) {
9         depth(root);
10         flag = false;
11     }
12     int depthLeft = nodeDepth.get(root.left) == null ? -1 : nodeDepth.get(root.left) ;
13     int depthRight = nodeDepth.get(root.right) == null ? -1 : nodeDepth.get(root.right) ;
14     return Math.abs(depthLeft - depthRight) < 2 && IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
15 }
16
17 public int depth(TreeNode node) {
18     if (node == null)   return -1;
19     int d = Math.max(depth(node.left), depth(node.right)) + 1;
20     nodeDepth.put(node, d);
21     return d;
22 }

 1 public boolean IsBalanced_Solution(TreeNode root) {
2     return getDepth(root) != -1;
3 }
4
5 public int getDepth(TreeNode node) {
6     if (node == null) return 0;
7     int left = getDepth(node.left);
8     if (left == -1) return -1;
9     int right = getDepth(node.right);
10     if (right == -1) return -1;
11     return Math.abs(left - right) > 1 ? -1 : Math.max(left, right) + 1;
12 }
posted @ 2019-12-16 09:15  努力学习的宵夜  阅读(...)  评论(...编辑  收藏