110. Balanced Binary Tree

Easy

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.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

    3
/ \
9 20
/ \
15 7

Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

       1
/ \
2 2
/ \
3 3
/ \
4 4

Return false.

package leetcode.easy;

/**
* Definition for a binary tree node. public class TreeNode { int val; TreeNode
* left; TreeNode right; TreeNode(int x) { val = x; } }
*/
public class BalancedBinaryTree {
public boolean isBalanced(TreeNode root) {
if (null == root) {
return true;
} else {
return (Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1) && isBalanced(root.left)
&& isBalanced(root.right);
}
} private static int maxDepth(TreeNode root) {
if (null == root) {
return 0;
} else {
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
} @org.junit.Test
public void test1() {
TreeNode tn11 = new TreeNode(3);
TreeNode tn21 = new TreeNode(9);
TreeNode tn22 = new TreeNode(20);
TreeNode tn33 = new TreeNode(15);
TreeNode tn34 = new TreeNode(7);
tn11.left = tn21;
tn11.right = tn22;
tn21.left = null;
tn21.right = null;
tn22.left = tn33;
tn22.right = tn34;
tn33.left = null;
tn33.right = null;
tn34.left = null;
tn34.right = null;
System.out.print(isBalanced(tn11));
} @org.junit.Test
public void test2() {
TreeNode tn11 = new TreeNode(1);
TreeNode tn21 = new TreeNode(2);
TreeNode tn22 = new TreeNode(2);
TreeNode tn31 = new TreeNode(3);
TreeNode tn32 = new TreeNode(3);
TreeNode tn41 = new TreeNode(4);
TreeNode tn42 = new TreeNode(4);
tn11.left = tn21;
tn11.right = tn22;
tn21.left = tn31;
tn21.right = tn32;
tn22.left = null;
tn22.right = null;
tn31.left = tn41;
tn31.right = tn42;
tn32.left = null;
tn32.right = null;
tn41.left = null;
tn41.right = null;
tn42.left = null;
tn42.right = null;
System.out.print(isBalanced(tn11));
}
}

最新文章

  1. linux-图形化远程管理协议
  2. 练习JavaScript实现梯形乘法表
  3. ASP.NET Web 应用程序及页面生命周期
  4. WPF MVVM模式下实现ListView下拉显示更多内容
  5. 数据结构与算法实验题7.1 M 商人的求救
  6. Windows-005-显示隐藏文件
  7. What Controls are new for windows phone 8.1
  8. Ioc注入方式写dubbo client(非set beans)
  9. java.util.AbstractStringBuilder源码分析
  10. 创建Java线程池
  11. pyspider安装后,点击run,报pyhton has stop working或python已停止运行的错误
  12. postgresql数据库导入导出
  13. hdu 4497 GCD and LCM 质因素分解+排列组合or容斥原理
  14. openwrt 的 inittab
  15. 安卓手机免root实现对其他软件最高管理(sandbox思想)
  16. 使用map做数组与链表去重
  17. windows 下的 Rsync 同步
  18. MySql数据and高级查询
  19. sql语句(一)— —判断是否有这条数据的优化
  20. idea中查看java类继承图

热门文章

  1. python 查询每周最后一个工作日
  2. tomcate环境搭建
  3. 多任务5-协程(IO密集型适用)--gevent完成多任务及monkey补丁
  4. TDOA基站 之 时间同步
  5. Java多线程下载初试
  6. SIGAI机器学习第四集 基本概念
  7. Postgresql pg_dump 与 pg_restore 使用举例
  8. CF798D Mike and distribution 贪心
  9. centos7 浏览器(firefox)中文乱码
  10. P3239 [HNOI2015]亚瑟王——概率DP