leetCode 110.Balanced Binary Tree (平衡二叉树) 解题思路和方法
2015-08-05 12:50
537 查看
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 of every node never differ by more than 1.
思路:判断是否是平衡二叉树,dfs即可,递归判断每个子树是否平衡二叉树,如果有子树不满足,则整体也不满足。
具体代码如下:
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
思路:判断是否是平衡二叉树,dfs即可,递归判断每个子树是否平衡二叉树,如果有子树不满足,则整体也不满足。
具体代码如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { /** * 判断是否平衡二叉树 * 看左右子树高度差是否超过1 * 不超过1则分别判断左右子树是否平衡二叉树 */ public boolean isBalanced(TreeNode root) { if(root == null) return true; if(dep(0,root) > - 10) return true; return false; } //计算树的高度 private int dep(int dep,TreeNode root){ if(root == null){ return dep-1; } int dep1 = dep(dep+1,root.left); int dep2 = dep(dep+1,root.right); //如果高度差超过1,返回-10 //则以后的dep返回值均为-10 if(Math.abs(dep1 - dep2) > 1){ return -10; } return dep1 > dep2 ? dep1 : dep2; } }
相关文章推荐
- 提高开发效率必须遵守的原则
- composer爆错:zlib_decode():data error
- js绘制圆形和矩形的方法
- android.os.NetworkOnMainThreadException 异常处理
- 对于多个未知的的条件的sql语句的写法
- 为什么只有grant usage权限却可以增删改查
- hdu2807The Shortest Path floyd
- Xcode 文档安装-iOS 8.1 Documentation
- 黑马程序员_Java基础:JDK1.5后的新特性:自动拆装箱,以及注意事项
- MDNavBarView下拉导航菜单(仿美团导航下拉菜单)
- Json转换利器Gson之实例二-Gson注解和GsonBuilder
- 接口与抽象类的区别
- AsyncTask我来给你扯会蛋
- LeeCode 109.Convert Sorted List to Binary Search Tree(将排序链表转化为BST) 解题思路和方法
- OC
- Linux病毒研究与分析
- inline陷阱问题
- StringUtils方法全集
- 多听多想少说(转)
- windows下动态链接库的使用(实例)