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]