Algorithms—110.Balanced Binary Tree
2015-09-08 16:34
369 查看
思路:比较左树和右树的深度,如果相差不超过1,继续判断左树和右树是否为平衡树。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if (root==null) {
return true;
}
if (Math.abs(f(root.left)-f(root.right))>1) {
return false;
}
return isBalanced(root.left)&&isBalanced(root.right);
}
public int f(TreeNode root){
if (root==null) {
return 0;
}else {
return 1+Math.max(f(root.left), f(root.right));
}
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isBalanced(TreeNode root) {
if (root==null) {
return true;
}
if (Math.abs(f(root.left)-f(root.right))>1) {
return false;
}
return isBalanced(root.left)&&isBalanced(root.right);
}
public int f(TreeNode root){
if (root==null) {
return 0;
}else {
return 1+Math.max(f(root.left), f(root.right));
}
}
}
相关文章推荐
- Django架设blog步骤
- Goods:我的订单查询分页
- Golang在京东列表页实践总结
- 11292 - Dragon of Loowater(贪心)
- Google Analytics自定义广告系列
- Beego环境搭建和bee工具安装使
- 算法系列(一) Google方程式
- 移除百度地图LOGO和版权信息
- Category添加属性
- Leetcode Algorithm No.242 Valid Anagram
- 【Django】template中实现加减乘除数学运算[加法 减法 乘法 除法]
- oc中protocol、category和继承的区别
- oc中protocol、category和继承的区别
- 【Django】 终端打印出错信息
- 【Django】 密码加密
- 【Django】 国际化
- [译]Google新logo是如何缩减13000字节的
- 【Django】 上传图片
- uva 11090 Going in Cycle!! 平均权值最小的回路
- 15条谷歌轶事