输入一棵二叉树,判断该二叉树是不是平衡二叉树。node
在作这题是,我第一反应就是遍历两次二叉树。第一遍记录每一个节点的深度,并将信息存入HashMap中,key = node,value = depth。第二遍再遍历一次二叉树,同时判断每一个节点是否是都是平衡二叉树。但这个方法并非最优的,没有进行剪枝,增长了很多没必要要的开销,并且使用了更多的额外空间。spa
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 }
在提交完代码后,我看到解题思路分享里有一个更棒的方法,做者是丁满历险记。他的方法从下往上遍历,若是子树是平衡二叉树,则返回子树的高度;若是发现子树不是平衡二叉树,则直接中止遍历,这样至多只对每一个结点访问一次。code
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 }