lintcode--平衡二叉树
来源:互联网 发布:手机电影网php源码 编辑:程序博客网 时间:2024/06/10 03:13
给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
给出二叉树 A={3,9,20,#,#,15,7}
, B={3,#,20,15,7}
A) 3 B) 3 / \ \ 9 20 20 / \ / \ 15 7 15 7
二叉树A是高度平衡的二叉树,但是B不是
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* 先求出左右字树的最大深度(递归);
* 再递归判断是否平衡
*/
public int maxDepth(TreeNode root){
if(root ==null){
return 0;
}
int leftLen = 0 ;
int rightLen = 0;
leftLen = maxDepth(root.left);
rightLen = maxDepth(root.right);
return leftLen>rightLen?leftLen+1:rightLen+1;
}
public boolean isBalanced(TreeNode root) {
// write your code here
if(root == null){
return true;
}
int leftLen = maxDepth(root.left);
int rightLen = maxDepth(root.right);
if((leftLen - rightLen)>1 || (rightLen-leftLen)>1){
return false;
}
return isBalanced(root.left)&&isBalanced(root.right);
}
}
- LintCode:平衡二叉树
- 平衡二叉树,lintcode
- lintcode平衡二叉树
- LintCode 平衡二叉树
- 平衡二叉树-LintCode
- lintcode--平衡二叉树
- 平衡二叉树-LintCode
- LintCode 平衡二叉树
- lintcode-平衡二叉树 -93
- LintCode 93-平衡二叉树
- LintCode | 93. 平衡二叉树
- LintCode | 93. 平衡二叉树
- LintCode 93.平衡二叉树
- lintcode balanced-binary-tree 平衡二叉树
- Lintcode-递归-93 平衡二叉树
- LintCode之93 平衡二叉树
- 【LintCode-93】平衡二叉树(Java实现-递归算法)
- 平衡二叉树平衡法则
- Myql操作使用(二)
- hibernate随笔(知识盲点)
- 颠覆平庸:在技术上持续精进
- Java对List中的中文属性按照拼音排序
- 【JS】关键词 in
- lintcode--平衡二叉树
- C++ Primer Plus 第6版 编程题参考答案(1)
- 【CodeForces
- in typeof instanceof ===这些运算符有什么作用
- JAVA集合类(大公司面试喜欢问的)
- React Native 生命周期
- hdu 6129 Just do it (杨辉三角)
- BZOJ——1452
- SharePreferences源码分析(commit与apply的区别以及原理)