4.1 isBalanced tree
来源:互联网 发布:动漫手机壳淘宝哪家店 编辑:程序博客网 时间:2024/06/16 16:07
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.
O(N2)soln
public class Solution {
public boolean isBalanced(TreeNode root) {if (root==null) return true;
if(Math.abs(depth(root.right)-depth(root.left))>1) return false;
return isBalanced(root.left)&&isBalanced(root.right);
}
private int depth(TreeNode node){
if(node==null) return 0;
if (node.left==null&& node.right==null) return 1;
return 1+Math.max(depth(node.right),depth(node.left));
}
}
0(N) time and 0(H) space,soln
public boolean isBalanced(TreeNode root) {
if (root==null) return true;
if(checkDept(root)<0)return false;
return true;
}
private int checkDept(TreeNode node){
if(node==null) return 0;
if (node.left==null&& node.right==null) return 1;
if(checkDept(node.left)<0||checkDept(node.right)<0) return -1;
if (Math.abs(checkDept(node.left)-checkDept(node.right))>1) return -1;
return 1+Math.max(checkDept(node.left),checkDept(node.right));
}
}
- 4.1 isBalanced tree
- IsBalanced
- Leetcode: isBalanced
- isBalanced平衡树
- Tree
- tree
- tree
- TREE
- Tree
- Tree
- tree
- tree
- tree
- tree
- tree
- tree
- Tree
- Tree
- 【SEO 决胜网络索引】 课程大纲及第一部分第一课:网络营销战略中的索引
- 【C语言探索之旅】 第一部分第七课:循环语句
- 【C语言探索之旅】 第一部分第八课:第一个C语言小游戏
- 图结构(二)- 邻接矩阵无向图
- 【C语言探索之旅】 第一部分第九课:函数
- 4.1 isBalanced tree
- 【C语言探索之旅】 第一部分第十课:练习题+习作
- 给肥胖的VS2005去掉Unicode VC++ unicode ANSI 版本转换
- C Programing Lanuage Notes
- 31. Next Permutation Leetcode Python
- 163 退溪 李滉
- PHP 数据类型
- 网络背景下商务英语专业学生文化意识培养的特点及策略
- 【将金令】1.22早评:金银扶摇而上,谨防空头突袭