Leetcode 110. Balanced Binary Tree

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 110. Balanced Binary Tree相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 110. Balanced Binary Tree 递归求解

[LeetCode]题解(python):110 Balanced Binary Tree

leetcode-110. Balanced Binary Tree

LeetCode_110. Balanced Binary Tree

Leetcode 110. Balanced Binary Tree

leetcode 110. Balanced Binary Tree