LeetCode#110 Balanced Binary Tree

Problem Definition:

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.

 

这里面临的问题是,既要记录子树的高度,又要记录子树是否平衡。

Solution 1: 只记录子树是否平衡,每次都重新计算高度,太耗时。

Solution 2: 用一个tuple来记录高度和平衡。

 1     # @param {TreeNode} root
 2     # @return {boolean}
 3     def isBalanced(root):
 4         b,h=func(root)
 5         return b
 6 
 7     def func(root):
 8         if root==None:
 9             return (True,0)
10         lb,lh=func(root.left)
11         rb,rh=func(root.right)
12         return (abs(lh-rh)<=1 and lb and rb, max(lh,rh)+1)
13     

 

 

Solution 3: 把这两个变量结合在一起,用一个负数表示不平衡时的高度。

 1     def isBalanced(self, root):
 2         return self.height(root)!=-1
 3 
 4     def height(self,root):
 5         if root==None:
 6             return 0
 7         hl=self.height(root.left)
 8         hr=self.height(root.right)
 9         if hl==-1 or hr==-1 or abs(hl-hr)>1:
10             return -1
11         return max(hl,hr)+1

 

posted @ 2015-07-21 21:39  曾可爱  阅读(101)  评论(0编辑  收藏  举报