leetcode(30).110. Balanced Binary Tree
来源:互联网 发布:java哈希表 编辑:程序博客网 时间:2024/06/06 05:30
题意:判断给定的二叉树是否是平衡树。(平衡树是指树的子树结点高度差不超过一)
初步分析:
深度考虑深度优先搜索,采用递归的方式实现。再比较判断高度差是否超过1.
我们可以把递归的部分设置为高度
然后,现在我们可以获得子树的高度了,那么左子树和右子树的高度差不能超过1。
然而,仅仅这样是错的。
比如
*
* *
* *
*
根节点的左子树和右子树虽然只差了1.,但是对于左子树
*
*
*
显然是不平衡的。
所以,判断平衡也是递归的,不仅自己要平衡,还要递归的判断左子树和右子树也是平衡的。
public class Solution { public boolean isBalanced(TreeNode root) { if (root == null) return true; return (Math.abs(getHeight(root.left) - getHeight(root.right)) < 2) && isBalanced(root.left) && isBalanced(root.right); } public int getHeight(TreeNode root) { if (root == null) return 0; return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); }}
把非递归判断和递归分开也不无不可
public class Solution { public boolean isBalanced(TreeNode root) { if (root == null) return true; if(Math.abs(getHeight(root.left) - getHeight(root.right)) > 1) return false; return isBalanced(root.left) && isBalanced(root.right); } public int getHeight(TreeNode root) { if (root == null) return 0; return 1 + Math.max(getHeight(root.left), getHeight(root.right)); }}
0 0
- leetcode(30).110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- [LeetCode]110.Balanced Binary Tree
- 【LeetCode】110.Balanced Binary Tree
- [Leetcode] 110. Balanced Binary Tree
- LeetCode --- 110. Balanced Binary Tree
- [leetcode] 110.Balanced Binary Tree
- [leetcode]110. Balanced Binary Tree
- LeetCode:110. Balanced Binary Tree
- 110. Balanced Binary Tree LeetCode
- [LeetCode]110. Balanced Binary Tree
- Leetcode 110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- LeetCode *** 110. Balanced Binary Tree
- leetcode 110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- #leetcode#110. Balanced Binary Tree
- Tips:replace()
- Socket通讯
- 如何阅读一本书(程序员)
- 安卓Andriod使用入门(二十)【颜色对话框】
- 数据挖掘分类算法之贝叶斯分类法原理及C++实现
- leetcode(30).110. Balanced Binary Tree
- 莎士比亚的对白
- QtWebkit读取html元素
- 与他人分享是学习过程中效率最高的方法
- 面向对象内容
- [入门-1]基础类型之列表
- Log4j 打印堆栈信息
- [kuangbin带你飞]专题九 连通图 B - Network (双连通分量(割点)(割边,桥))(模板)
- 太多的.hive-stagingxxx文件的处理