剑指offer-39:平衡二叉树

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。

解题思路

在做这题是,我第一反应就是遍历两次二叉树。第一遍记录每个节点的深度,并将信息存入HashMap中,key = node,value = depth。第二遍再遍历一次二叉树,同时判断每个节点是不是都是平衡二叉树。但这个方法并不是最优的,没有进行剪枝,增加了不少不必要的开销,而且使用了更多的额外空间。

 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  我是宵夜  阅读(196)  评论(0编辑  收藏  举报