LeetCode: Balanced Binary Tree 解题报告
2014-12-18 20:54
281 查看
[b]Balanced Binary Tree [/b]
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.
Show Tags
View Code
GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/IsBalanced.java
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.
Show Tags
// Solution 2: public boolean isBalanced(TreeNode root) { if (root == null) { return true; } boolean cut = false; if (root.right == null || root.left == null) { cut = true; } return isBalanced(root.left) && isBalanced(root.right) && Math.abs(getDepth(root.left, cut) - getDepth(root.right, cut)) <= 1; } public int getDepth(TreeNode root, boolean cut) { if (root == null) { return -1; } if (cut && (root.left != null || root.right != null)) { // if another tree is not deep, just cut and return fast. // Improve the performance. return 2; } return 1 + Math.max(getDepth(root.left, false), getDepth(root.right, false)); }
View Code
GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/IsBalanced.java
相关文章推荐
- LeetCode解题报告 110. Balanced Binary Tree [easy]
- LeetCode解题报告 110. Balanced Binary Tree
- 【LeetCode】Balanced Binary Tree 算法优化 解题报告
- Leetcode 110. Balanced Binary Tree 平衡二叉树 解题报告
- 【LeetCode】Balanced Binary Tree 解题报告
- [LeetCode]Balanced Binary Tree,解题报告
- [leetcode] 110. Balanced Binary Tree 解题报告
- 【LeetCode】Balanced Binary Tree 解题报告
- [leetcode]110. Balanced Binary Tree@Java解题报告
- LeetCode(110) Balanced Binary Tree解题报告
- 【LeetCode】110. Balanced Binary Tree(Easy)解题报告
- [Leetcode] 110. Balanced Binary Tree 解题报告
- [Leetcode] 637. Average of Levels in Binary Tree 解题报告
- [leetcode] 105. Construct Binary Tree from Preorder and Inorder Traversal 解题报告
- [leetcode] 236. Lowest Common Ancestor of a Binary Tree 解题报告
- 【LeetCode】Serialize and Deserialize Binary Tree 解题报告
- 【LeetCode】108.Convert Sorted Array to Binary Search Tree(Easy)解题报告
- 景岁的Leetcode解题报告:297. Serialize and Deserialize Binary Tree(Python)
- LeetCode(111) Minimum Depth of Binary Tree解题报告
- [Leetcode] 108. Convert Sorted Array to Binary Search Tree 解题报告