110. Balanced Binary Tree
Posted 我的名字叫周周
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了110. Balanced Binary Tree相关的知识,希望对你有一定的参考价值。
/* * 110. Balanced Binary Tree * 2016-5-17 by Mingyang * This improved algorithm works by checking the height of each subtree as we recurse * down from the root. On each node, we recursively get the heights of the left and right * subtrees through the checkHeight method. If the subtree is balanced, then check- * Height will return the actual height of the subtree. If the subtree is not balanced, then * checkHeight will return -1. We will immediately break and return -1 from the current call. * 自己刚开始做的时候,在主函数里面吧后面两个条件一起写在一个语句里面了,殊不知base case里面并没有false的statement */ /* *Wrong one: *return isBalanced(root.left)&&isBalanced(root.right)&&(Math.abs(depth(root.left)-depth(root.right))<=1); *太傻叉了这种写法,基本的递归都不会,base case都没写好,如何写递归? *以后写递归以前,一定要知道哪些基本case,都没有return false的情况,就会进入死循环。 */ public boolean isBalanced(TreeNode root) { if (root == null) return true; if (Math.abs(depth(root.left) - depth(root.right)) > 1) return false; return isBalanced(root.left) && isBalanced(root.right); } private int depth(TreeNode root) { if (root == null) return 0; return Math.max(depth(root.left), depth(root.right)) + 1; }
以上是关于110. Balanced Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章