Tree110BalancedBinaryTree
来源:互联网 发布:plc与dcs编程的区别 编辑:程序博客网 时间:2024/06/05 00:52
Attention
the definition of “balanced” here is for “the depths of the two sub trees”, not “the depths of all the leaves”.
思路
- Level Traversal, check the number of each level equals
2^height
Or not. Failed Case 2- Actually it is ’ the depths of all leaves’ as Attention listed.
- Fine the node that ‘made’ the differ of height
- If one of its child is null, check its child’s child exist or not.
- Logic is wrong. See Fail Case 1
- Return the height of each child.
- Check itself is balanced and check its child
- Recursive one takes 3ms
- Actually we can use non-recursive one. The only reason to use it is because —– The “raw content”干货 of this function is very small, just comparing the height of two sub-trees.
Failed case
- 只考虑了difference在同一个节点的情况,没考虑不同节点。思路2不正确
Input: [1,2,2,3,3,null,null,4,4]
Output: true
Expected: false - 思路1也不正确,并没有真正读题,以下情况应该返回1
Input:[1,2,2,3,3,3,3,4,4,4,4,4,4,null,null,5,5]
Output:false
Expected:true
TIPS
- 一旦看到IfElse的return很简单,可以写成?:形式,这样比较简明,不然太繁杂
- 叠加的else可以简化
Original getDepth()
private static int getDepth(TreeNode root) { if (root == null) return 0; int leftDepth = getDepth(root.left); //If the left child is balanced, we search the other one if (leftDepth != -1) { int rightDepth = getDepth(root.right); //If the right child is balanced if (rightDepth != -1) { if (Math.abs(leftDepth - rightDepth) > 1 ) {return -1;} else { return 1 + Math.max(leftDepth, rightDepth);} } else { return -1;//This can be simplized in the end of the function. } } else { return -1; } }
简化后为
private static int getDepth(TreeNode root) { if (root == null) return 0; int leftDepth = getDepth(root.left); //If the left child is balanced, we search the other one if (leftDepth != -1) { int rightDepth = getDepth(root.right); //If the right child is balanced if (rightDepth != -1) { return Math.abs(leftDepth - rightDepth) > 1 ? -1 : 1 + Math.max(leftDepth, rightDepth); } } return -1; }
0 0