Balanced Binary Tree
来源:互联网 发布:linux设置root密码 编辑:程序博客网 时间:2024/06/15 10:43
1.题目
给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
样例
给出二叉树 A={3,9,20,#,#,15,7}
, B={3,#,20,15,7}
A) 3 B) 3 / \ \ 9 20 20 / \ / \ 15 7 15 7
二叉树A是高度平衡的二叉树,但是B不是
2.算法
这个题目的思路是用递归,记录左右子树最深长度,然后比较
public boolean isBalanced(TreeNode root) { // write your code here return helper(root) >= 0; } public int helper(TreeNode root) { if (root == null) { return 0; } int left = helper(root.left); int right = helper(root.right); if (left < 0 || right < 0) //如果有一边不满足条件,则返回-1 { return -1; } if (Math.abs(left - right) >= 2) //两边子树差与2比较 { return -1; } return Math.max(left, right) + 1;//取最大的深度 }
0 0
- Balanced binary tree 扩展
- LeetCode: Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [Leetcode] Balanced Binary Tree
- LeetCode : Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- Balanced Binary Tree
- Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- Balanced Binary Tree
- Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- [Leetcode]Balanced Binary Tree
- [leetcode]Balanced Binary Tree
- Android 照相机拍照,压缩后储存于SD卡
- 安卓控件——AutoCompleteTextView和MultiAutoCompleteTextView实现自动匹配输入的内容
- Eclipse开发常用快捷键
- 编程式事务管理
- 泛型:改变变量值触发的事件
- Balanced Binary Tree
- Socket通信原理,TCP,UDP协议
- VS2015 生成.lib文件
- Solr 6.0 学习(十四)Solr RequstHandler
- Training Set, Validation Set 和Testing Set之间的差别及关系
- 三大卫视跨年晚会网络直播,竟都由这家企业负责,到底有啥背景?
- 这两天遇到的scikit-learn的问题
- mac 下用 brew 安装mongodb
- 【Centos 7】使用screen恢复终端连接