Leetcode Balanced Binary Tree
2016-07-19 04:50
274 查看
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.
Difficulty: Easy
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int height(TreeNode root){
if(root == null) return 0;
int left = height(root.left);
int right = height(root.right);
if(left == -1 || right == -1 || Math.abs(left - right) > 1)
return -1;
return 1 + Math.max(left, right);
}
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int left = height(root.left);
int right = height(root.right);
if(left == -1 || right == -1 || Math.abs(left - right) > 1)
return false;
return true;
}
}
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.
Difficulty: Easy
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int height(TreeNode root){
if(root == null) return 0;
int left = height(root.left);
int right = height(root.right);
if(left == -1 || right == -1 || Math.abs(left - right) > 1)
return -1;
return 1 + Math.max(left, right);
}
public boolean isBalanced(TreeNode root) {
if(root == null) return true;
int left = height(root.left);
int right = height(root.right);
if(left == -1 || right == -1 || Math.abs(left - right) > 1)
return false;
return true;
}
}
相关文章推荐
- Leetcode Divide Two Integers
- Leetcode Sqrt(x)
- Leetcode Number of Digit One
- Leetcode Largest Number
- Leetcode Word Break II
- [leetcode] 118. Pascal's Triangle
- php判断是否为今天
- Codeforces Round #327 (Div. 2)
- 决策树算法(四)——选取最佳特征划分数据集
- 一键安装LAMP或LNMP
- [leetcode] 110. Balanced Binary Tree
- Leetcode 299. Bulls and Cows (Python)
- redhat7.2用户及用户组权限管理操作实例
- zabbix redis_low_level_discovery
- OSChina 周二乱弹 ——风流不需编码强,红袖无言意最长
- rename datafile 做了什么
- Leetcode 373. Find K Pairs with Smallest Sums(Python)
- [LeetCode] 66. Plus One
- CnCrypt代码 之 为磁盘设备分配和移除盘符
- HDU 2203 亲和串