Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def isBalanced(root):
- if root == None:
- return -1
- lh = isBalanced(root.left)
- rh = isBalanced(root.right)
- if lh == -2 or rh == -2:
- return -2
- if abs(lh - rh) > 1:
- return -2
- return max(lh, rh) + 1
- def isBalanced(root):
- nodes = [root]
- results = []
- while nodes:
- node = nodes.pop()
- if node is None:
- results.append(-1)
- else if node == 0: # 0 is a flag we use for when we are ready to combine results
- lh = results.pop()
- rh = results.pop()
- if abs(lh - rh) > 1:
- return -2 # we could have continued with the stack; this is just a shortcut
- else:
- results.append(max(lh, rh) + 1)
- else:
- nodes.push(0)
- nodes.push(node.left)
- nodes.push(node.right)
- return results, # results will have only one value
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement