码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 110. Balanced Binary Tree

时间:2016-12-19 11:14:50      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:self   return   problem   tree   nbsp   log   more   多次   key   

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 def isBalanced(self, root):
 2         """
 3         :type root: TreeNode
 4         :rtype: bool
 5         """
 6         if not root:
 7             return True
 8         factor = abs(self.level(root.left) - self.level(root.right))
 9         return factor < 2 and self.isBalanced(root.right) and self.isBalanced(root.left)
10 
11 def level(self, root):
12         if not root:
13             return 0
14         return max(self.level(root.left), self.level(root.right)) + 1

这里的方法使用了递归,每个subtree会多次计算level。虽然可以通过OJ, 但是可以使用DP提高效率。 建立一个Hash table, root作为key, level函数的值作为value。
 1 d = {}
 2 class Solution(object):
 3     def isBalanced(self, root):
 4         """
 5         :type root: TreeNode
 6         :rtype: bool
 7         """
 8         if not root:
 9             return True
10         factor = abs(self.level(root.left) - self.level(root.right)) 
11         return factor < 2 and self.isBalanced(root.left) and self.isBalanced(root.right)
12         
13     def level(self, root):
14         if not root:
15             return 0
16         
17         if root in d:
18             return d[root]
19         else:
20             d[root] = max(self.level(root.left), self.level(root.right)) + 1
21             return d[root]

 

 

Leetcode 110. Balanced Binary Tree

标签:self   return   problem   tree   nbsp   log   more   多次   key   

原文地址:http://www.cnblogs.com/lettuan/p/6196380.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!