Balanced Binary Tree
来源:互联网 发布:linux 纯文本档 高亮 编辑:程序博客网 时间:2024/06/05 00:11
https://oj.leetcode.com/problems/balanced-binary-tree/
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofevery node never differ by more than 1.
public boolean isBalanced(TreeNode root)
这题看过CC150的人可能都会有一个误区,这个误区我用下面一段代码来表述:
public boolean isBalanced(TreeNode root) { return maxDepth(root) - minDepth(root) <= 1; } public int maxDepth(TreeNode root){ if(root == null) return 0; else return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; } public int minDepth(TreeNode root){ if(root == null) return 0; else return Math.min(minDepth(root.left), minDepth(root.right)) + 1; }
这段代码是错的。因为这代码判断的是完全二叉树,而不是平衡二叉树。平衡二叉树表示的是任意两棵子树的MaxDepth差不超过一就可以了。和这种完全二叉树还是有很大意义上的区别的。而这一题,是要比看上去稍微难那么一点点的。原因就在于它需要在每一棵子树上用一种自下向上的递归方法同时返回这棵子树左右两端的MaxDepth的同时也要返回这两棵子树是否isBalanced的。也就是此题暗含的另一个条件就是:平衡二叉树的所有子树都是平衡二叉树,只要有一个节点不对,那就全盘都不对了。要同时返回一个boolean和一个integer,看上去只能新开一个class来包含这两个元素了。但其实我们可以巧妙的用特殊的int来同时做到两点。事实上如果在某一点上我们判断出false的值,那么就没有必要再往上返回高度了。相反返回一个不可能达到的值譬如Integer.MIN_VALUE表示false就可以了。下面就给出代码:
public boolean isBalanced(TreeNode root) { return depth(root) != Integer.MIN_VALUE;//一旦返回的是实际的高度而不是MIN_VALUE就表示检测通过了 } public int depth(TreeNode root){ if(root == null) return 0; int left = depth(root.left); int right = depth(root.right); if(left == Integer.MIN_VALUE || right == Integer.MIN_VALUE)//两边有一边已经出错了。 return Integer.MIN_VALUE; else if(Math.abs(left - right) <= 1)//高度差小于1,继续返回高度。 return Math.max(left, right) + 1; else return Integer.MIN_VALUE;//高度差大于1。出错 }
0 0
- Balanced binary tree 扩展
- LeetCode: Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [Leetcode] Balanced Binary Tree
- LeetCode : Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- Balanced Binary Tree
- Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- Balanced Binary Tree
- Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- [Leetcode]Balanced Binary Tree
- [leetcode]Balanced Binary Tree
- http://wenku.baidu.com/album/view/bd0e2dea6294dd88d0d26bda.html
- 怎么充值贝贝游戏的银子
- 怎么充值贝贝游戏的银子
- JAVA复习知识点总结-基础篇
- 做自己的决定,自己的路自己走。
- Balanced Binary Tree
- LeetCode - Longest Substring Without Repeating Characters
- [codevs 1912] 汽车加油行驶问题
- Minimum Depth of Binary Tree
- go语言之整形和字节数组的转换
- DC简明教程
- 改装氙气灯
- 9.4 subset I and II,
- 【BZOJ3191】【JLOI2013】卡牌游戏 概率DP