[LeetCode]Balanced Binary Tree,解题报告
2013-12-02 10:21
387 查看
题目
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其次,理解题目后,很容易想到这是一道典型的递归题目(ps:特别是面试的时候,二叉树和递归联系的特别多,我面试豌豆荚也是考了一个类似的题目)
最后,首先判断根节点的左右子树高度差,相差大于1返回false,相差不大于1则继续递归的测试根节点的左子树和右子树
AC代码
public class BalancedBinaryTree { static class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { this.val = x; } } public static boolean isBalanced(TreeNode root) { if (root == null) return true; int lh = getHeight(root.left); int rh = getHeight(root.right); if (Math.abs(lh - rh) > 1) return false; return isBalanced(root.left) && isBalanced(root.right); } public static int getHeight(TreeNode root) { if (root == null) return 0; return Math.max(getHeight(root.left), getHeight(root.right)) + 1; } }
吐槽
csdn神马时候才能支持markdown语法编辑博客啊,如果到过年还不支持markdown,果断迁移到segmentfault上了相关文章推荐
- [Leetcode] 110. Balanced Binary Tree 解题报告
- Leetcode 110. Balanced Binary Tree 平衡二叉树 解题报告
- LeetCode解题报告 110. Balanced Binary Tree
- [leetcode] 110. Balanced Binary Tree 解题报告
- 【LeetCode】Balanced Binary Tree 算法优化 解题报告
- 【LeetCode】110. Balanced Binary Tree(Easy)解题报告
- LeetCode解题报告 110. Balanced Binary Tree [easy]
- 【LeetCode】Balanced Binary Tree 解题报告
- LeetCode(110) Balanced Binary Tree解题报告
- [leetcode]110. Balanced Binary Tree@Java解题报告
- 【LeetCode】Balanced Binary Tree 解题报告
- LeetCode: Balanced Binary Tree 解题报告
- [leetcode] 105. Construct Binary Tree from Preorder and Inorder Traversal 解题报告
- [leetcode] 236. Lowest Common Ancestor of a Binary Tree 解题报告
- 景岁的Leetcode解题报告:297. Serialize and Deserialize Binary Tree(Python)
- LeetCode(111) Minimum Depth of Binary Tree解题报告
- 【LeetCode】Validate Binary Search Tree 解题报告(Java & Python)
- [LeetCode]Binary Tree Postorder Traversal,解题报告
- 【LeetCode】Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- [LeetCode] Recover Binary Search Tree 解题报告