Leetcode: 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.
很锻炼DP/recursive思路的一道题,个人感觉DP/recursive算是比较难写的题目了。这道题解法的巧妙之处在于巧用-1,并且使用临时存储,节省了很多开支。这道题同时也在Career Cup上面出现过
这道题我两次调试通过,第一次错是因为input{}, output false, expected true
我的算法只有一层递归(因为巧用-1的原因),runs in O(N) time, andO(H) space
1 public class Solution { 2 public boolean isBalanced(TreeNode root) { 3 if (root == null) return true; 4 if (checkBalance(root) != -1) return true; 5 else return false; 6 } 7 8 public int checkBalance(TreeNode root) { 9 if (root == null) return 0; 10 int leftHeight = checkBalance(root.left); 11 int rightHeight = checkBalance(root.right); 12 if (leftHeight == -1 || rightHeight == -1) return -1; 13 else if (Math.abs(leftHeight - rightHeight) > 1) return -1; 14 return Math.max(leftHeight, rightHeight) + 1; 15 } 16 }
Leetcode: Balanced Binary Tree相关推荐
- leetcode - Balanced Binary Tree
题目:Balanced Binary Tree Given a binary tree, determine if it is height-balanced. For this problem, a ...
- LeetCode Balanced Binary Tree
Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary ...
- leetcode -- Balanced Binary Tree TODO
Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary ...
- Leetcode::Balanced Binary Tree
后序遍历,每个节点只遍历一次. 1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode ...
- LeetCode:Balanced Binary Tree
题目链接 Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced bi ...
- [LeetCode]Balanced Binary Tree
Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary ...
- LeetCode 110 Balanced Binary Tree 平衡二叉树
LeetCode 110 Balanced Binary Tree Given a binary tree, determine if it is height-balanced. For this ...
- LeetCode 110. 平衡二叉树(Balanced Binary Tree) 15
110. 平衡二叉树 110. Balanced Binary Tree 题目描述 给定一个二叉树,判断它是否是高度平衡的二叉树. 本题中,一棵高度平衡二叉树定义为: 一个二叉树每个节点的左右两个子树 ...
- LeetCode 110. Balanced Binary Tree
LeetCode 110. Balanced Binary Tree 本博客参考自:http://www.cnblogs.com/grandyang/p/4045660.html Solution1: ...
最新文章
- python培训班深圳-深圳哪里有Python培训班?
- vue 页面跳转的两种方式
- 年审是当月还是当天_车检是按月份还是日期 审车日期以什么为准
- Python基础(6)--条件、循环
- 动作定位、检测与理解,ICCV 2021 DeeperAction挑战赛开启~
- Jenkins 使用slave管理进行持续集成测试说明
- 中兴8912交换机show run故障处理
- 讨论生活中什么样东西可以何种变量描述找出生活中顺序执行事情用c语言,《C语言程序设计》实验指导书...
- Linux之重置密码的两种方法
- 计算机专业选电科还是华科,西交、华科与两电一邮:5所高校怎么选?工科选西交,学IT选北邮...
- C#中计算两个时间的差
- 怎么阻止acrobat自动更新升级?
- 拓端tecdat|通过SAS网络分析对人口迁移进行可视化分析
- 软件分享 AirPlayer
- 数据分析最常用的excel函数公式大全
- RO、RW和ZI数据解析
- 《C++程序设计上机实践及学习辅导》实验报告
- 【游戏开发创新】Unity+人工智能,让小朋友的画成真,六一儿童节一起来画猫猫吧(Unity | 人工智能 | 绘图 | 爬虫 | 猫妖)
- Linux下路由器的配置
- 星起航跨境—亚马逊发展现状及未来趋势分析