Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree was defined as a binary tree in which the depth of the Every node never differ by more than 1.
1 defisbalanced (self, root):2 """3 : Type Root:treenode4 : Rtype:bool5 """6 if notRoot:7 returnTrue8Factor = ABS (Self.level (Root.left)-Self.level (root.right))9 returnFactor < 2 andself.isbalanced (Root.right) andself.isbalanced (root.left)Ten One defLevel (self, root): A if notRoot: - return0 - returnMax (Self.level (Root.left), Self.level (root.right)) + 1
The method here uses recursion, and each subtree calculates the level multiple times. Although it is possible to pass OJ, you can use DP to improve efficiency. Create a hash table, root as key, and the level function as value.
1D = {}2 classsolution (object):3 defisbalanced (self, root):4 """5 : Type Root:treenode6 : Rtype:bool7 """8 if notRoot:9 returnTrueTenFactor = ABS (Self.level (Root.left)-Self.level (root.right)) One returnFactor < 2 andself.isbalanced (Root.left) andself.isbalanced (root.right) A - defLevel (self, root): - if notRoot: the return0 - - ifRootinchD: - returnD[root] + Else: -D[root] = max (Self.level (Root.left), Self.level (root.right)) + 1 + returnD[root]
Leetcode 110. Balanced Binary Tree