Balanced Binary Tree
来源:互联网 发布:php架构师面试题 编辑:程序博客网 时间:2024/05/22 13:50
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.
解题思路:首先比较两颗树的高度,比较是不是balance,然后再比较左子树和右子树是不是balance。
public class Solution {
public boolean isBalanced(TreeNode root) {
if(root==null) return true;
TreeNode left = root.left;
TreeNode right = root.right;
int diff = Math.abs(getHeight(left) - getHeight(right));
if(diff > 1) return false;
return isBalanced(left) && isBalanced(right);
}
public int getHeight(TreeNode root) {
if(root == null) return 0;
return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
}
}
参考博文http://blog.sina.com.cn/s/blog_71d59f9a01018fyh.html
- Balanced binary tree 扩展
- LeetCode: Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [Leetcode] Balanced Binary Tree
- LeetCode : Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- Balanced Binary Tree
- Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- Balanced Binary Tree
- Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- [Leetcode]Balanced Binary Tree
- [leetcode]Balanced Binary Tree
- llvm-clang和llvm-gcc
- 使用 Java 实现 Comet 风格的 Web 应用
- Android APK反编译查看源码及资源文件
- 模拟真实物体运动的js动画库插件-Anima
- c# 中值类型和引用类型
- Balanced Binary Tree
- 排序算法三:直接插入排序
- 九度 题目1011:最大连续子序列
- MapReduce 2.0 in Apache Hadoop 0.23
- Impulse Train
- Python CSV初用
- 九度 题目1012:畅通工程 (BFS计算连通分支的个数)
- protocol buffer使用范例5
- java 使用 comet4j 主动向客户端推送信息 简单例子