题目:

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.

思路:

1) 计算结点的高度,但这个有重复计算

package tree;

public class BalancedBinaryTree {

    public boolean isBalanced(TreeNode root) {
if (root == null) return true;
int leftHeight = height(root.left);
int rightHeight = height(root.right);
return Math.abs(leftHeight - rightHeight) <= 1 &&
isBalanced(root.left) && isBalanced(root.right);
} private int height(TreeNode root) {
if (root == null) return 0;
return Math.max(1 + height(root.left), 1 + height(root.right));
} }

2) 不进行重复计算,但需要new 对象,反而也花时间

package tree;

public class BalancedBinaryTree {

    class Entry{
public int height;
public boolean balanced;
} public boolean isBalanced(TreeNode root) {
return checkTree(root).balanced;
} private Entry checkTree(TreeNode root) {
Entry entry = new Entry();
if (root == null) {
entry.height = 0;
entry.balanced = true;
} else {
Entry left = checkTree(root.left);
Entry right = checkTree(root.right);
entry.height = Math.max(left.height, right.height) + 1;
entry.balanced = Math.abs(left.height - right.height) <= 1 && left.balanced && right.balanced;
}
return entry;
} }

最新文章

  1. 五、基于hadoop的nginx访问日志分析--userAgent和spider
  2. paxos(chubby) vs zab(Zookeeper)
  3. 搭建自己的apache tomcat php mysql 环境和WordPress站点制作
  4. PHPExcel--基本操作
  5. Salesforce 动态审批
  6. jQuery常用的插件及功能汇总-持续
  7. AngularJS in Action读书笔记5(实战篇)——在directive中引入D3饼状图显示
  8. Java 线程池的原理与实现
  9. Win2008 IIS7日期时间格式更改最简便方法
  10. 虚拟化之kvm与xen对比
  11. Sublime Text 2/3安装CTags实现函数跳转
  12. c#基础-----数据类型,转义字符,引用类型,类型转换
  13. ES6中的迭代器(Iterator)和生成器(Generator)
  14. 泛微关于js设计的一些小技巧
  15. socket(TCP-粘包)通讯之Python实现
  16. [Day19]Collection接口中的子类(List集合、Set集合)
  17. Django---框架简介和工程搭建
  18. 每月IT摘录201904
  19. 【rabbitmq】Centos7 下安装rabbitmq
  20. ES使用org.elasticsearch.client.transport.NoNodeAvailableException: No node available 错误解决方法

热门文章

  1. SQL语句中,Conversion failed when converting datetime from character string.错误的解决办法
  2. Unity3d热更新全书-加载(一)从AssetBundle说起
  3. mac 命令行批量删除.svn[转]
  4. 切换到ZSH以后遇到的坑
  5. Windows 10 周年版尝鲜
  6. sigar
  7. 知方可补不足~sqlserver中的几把锁~续
  8. Atitit 项目培训与学校的一些思路总结
  9. mysql创建数据库
  10. 隐藏自定义tabbar(关于tabbar的hide属性对于自定义无效)