LeetCode Balanced Binary Tree
2015-07-07 09:19
148 查看
Description:
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.
Solution:
先dfs求出每个节点的做右子树的深度,然后想减大于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.
Solution:
先dfs求出每个节点的做右子树的深度,然后想减大于1就表示不平衡,用一个“全局”的布尔类型变量记录一下。
import java.util.*; public class Solution { boolean flag = true; public boolean isBalanced(TreeNode root) { depth(root); return flag; } int depth(TreeNode root) { if (root == null) return 0; int left_dep = depth(root.left); int right_dep = depth(root.right); if (Math.abs(left_dep - right_dep) > 1) flag = false; return Math.max(left_dep, right_dep) + 1; } }
相关文章推荐
- 指针数组与数组指针区别
- 性能:15个JavaScript本地存储技术的函数库和工具
- DbContext 和ObjectContext两者的区别
- Xcode7 更新之后遇到的新问题
- 29、chgrp命令
- vim随想笔记(1)
- WIZnet官方网盘
- 【数据库设计-1.1】关系的实现
- hadoop2安装错误记录
- android游戏开发基础(绘图类)
- 【LeetCode 67_字符串_算术运算】Add Binary
- sqlserver -- 学习笔记(六)日期格式转换
- C#调用C/C++动态库 封送结构体,结构体数组
- Lync 2013 Web Scheduler部署
- 神经网络识别车牌字符
- [管理篇]VMWare搭建Openstack——Cinder的使用以及相关操作
- 通过位运算交换a 和 b
- 浏览器中url存储的JavaScript实现
- JDK的安装配置
- C#中方法、类等的默认访问修饰符