Leetcode no. 110
2016-05-26 21:11
302 查看
110. Balanced Binary Tree
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.
/**
* 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) {
return maxDepth(root)==-1 ? false : true;
}
private int maxDepth(TreeNode root){
if (root==null) return 0;
int left= maxDepth(root.left);
int right= maxDepth(root.right);
if (left==-1 || right==-1 || Math.abs(left-right)>1) return -1;
return Math.max(left,right)+1;
}
}
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.
/**
* 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) {
return maxDepth(root)==-1 ? false : true;
}
private int maxDepth(TreeNode root){
if (root==null) return 0;
int left= maxDepth(root.left);
int right= maxDepth(root.right);
if (left==-1 || right==-1 || Math.abs(left-right)>1) return -1;
return Math.max(left,right)+1;
}
}
相关文章推荐
- exec()函数
- node前端自动化
- # USACO4.4 三道题
- cf#354
- 链表,纠错!
- 最可怕的是牛人还那么努力
- Linux grep用法整理
- C++面试笔记--STL模板与容器
- 随手摘录
- 应用类App框架搭建 之框架分析(待续)
- 轮播小圆点
- IOS-Frameworks-UIKit-UIApplication-UIApplicationDelegate
- oracle将A表数据复制到B表中
- JAVA 常用时间日期计算转换方法
- MongoDB快速入门学习笔记3 MongoDB的文档插入操作
- UEFI安装Win10
- python之list、tuple、dict、set对比
- bash 函数
- 10317 Fans of Footbal Teams
- 15 SpringMVC_处理模型数据之Map