leedcode做题总结,题目Balanced Binary Tree 2012/10/08
2014-07-12 21:08
561 查看
检测平衡二叉树,应该算是很简单的题目了,递归每个节点先求出左右子树的高,如果相差小于2在判断子节点们是不都平衡
Update 2015/08/17: 上面的答案不好,isBalanced()是从上往下递归,每一次都用调用hig在此从上往下递归,所以很多计算是重复的,这道题应该从下往上计算,一边计算高度一边判断,方法如下:
public int hig(TreeNode root){ if(root==null)return 0; return Math.max(hig(root.left),hig(root.right))+1; } public boolean isBalanced(TreeNode root) { if(root==null) return true; if(Math.abs(hig(root.left)-hig(root.right))<2) return isBalanced(root.left)&&isBalanced(root.right); else return false; }
Update 2015/08/17: 上面的答案不好,isBalanced()是从上往下递归,每一次都用调用hig在此从上往下递归,所以很多计算是重复的,这道题应该从下往上计算,一边计算高度一边判断,方法如下:
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: True if this Binary tree is Balanced, or false. */ public int check(TreeNode node){ if (node == null){ return 0; } int lheight = check(node.left); int rheight = check(node.right); if (lheight == -1 || rheight == -1){ return -1; } if (Math.abs(lheight - rheight) > 1){ return -1; } return Math.max(lheight, rheight) + 1; } public boolean isBalanced(TreeNode root) { // write your code here if (check(root) == -1) return false; return true; } }
相关文章推荐
- leedcode做题总结,题目Binary Tree Zigzag Level Order Traversal 2012/09/28
- leedcode做题总结,题目Maximum Depth of Binary Tree-------2012/09/29
- leedcode做题总结, 题目Construct Binary Tree from Preorder。。。105/106
- leedcode做题总结,题目Binary Tree Preorder Traversal 2013/11/05
- leedcode做题总结,题目Convert Sorted Array to Binary Search Tree 2013/02/18
- leedcode做题总结, 题目Unique Binary Search TreesI/II95/96
- leedcode做题总结,题目Same Tree 2012/09/03
- leedcode做题总结,题目Reorder List 13/11/12
- leedcode做题总结,题目Reverse Integer----- 2011/12/25
- leedcode做题总结,题目Pascal's Triangle I/II-------2012/10/28
- leedcode做题总结, 题目Find Minimum in Rotated Sorted Array I/II
- leedcode做题总结,题目Remove Element 2012/02/16
- leedcode做题总结,题目Minimum Depth of Binary Tree 2012/10/09
- leedcode做题总结,题目Binary Tree Level Order TraversalI/II 2012/09/28
- leedcode做题总结, 题目Permutations I/II46/47
- leedcode做题总结,题目Gas Station-------- 2013/09/28
- leetcode做题总结,题目Convert Sorted List to Binary Search Tree 2012/10/02
- leedcode做题总结,题目Sum Root to Leaf Numbers 2013/02/18
- leedcode做题总结, 题目Longest Palindromic Substring 5
- leedcode做题总结,题目Flatten Binary Tree to Linked List 2012/10/14