Advertisement
Guest User

Untitled

a guest
Apr 18th, 2014
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. def isBalanced(root):
  2. if root == None:
  3. return -1
  4.  
  5. lh = isBalanced(root.left)
  6. rh = isBalanced(root.right)
  7.  
  8. if lh == -2 or rh == -2:
  9. return -2
  10.  
  11. if abs(lh - rh) > 1:
  12. return -2
  13.  
  14. return max(lh, rh) + 1
  15.  
  16. def isBalanced(root):
  17. nodes = [root]
  18. results = []
  19. while nodes:
  20. node = nodes.pop()
  21. if node is None:
  22. results.append(-1)
  23. else if node == 0: # 0 is a flag we use for when we are ready to combine results
  24. lh = results.pop()
  25. rh = results.pop()
  26. if abs(lh - rh) > 1:
  27. return -2 # we could have continued with the stack; this is just a shortcut
  28. else:
  29. results.append(max(lh, rh) + 1)
  30. else:
  31. nodes.push(0)
  32. nodes.push(node.left)
  33. nodes.push(node.right)
  34. return results, # results will have only one value
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement