Guest User

Untitled

a guest
Sep 24th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.17 KB | None | 0 0
  1. # Python3
  2.  
  3. # Definition for a binary tree node.
  4. # class TreeNode:
  5. # def __init__(self, x):
  6. # self.val = x
  7. # self.left = None
  8. # self.right = None
  9.  
  10. class Solution:
  11. def postorderTraversal(self, root):
  12. """
  13. :type root: TreeNode
  14. :rtype: List[int]
  15. """
  16.  
  17. # approach: use iteration
  18.  
  19. stack = []
  20. result = []
  21. current = root
  22.  
  23. while current or len(stack):
  24. # push right children if it exists then current root
  25. # then down to left children
  26. while current:
  27. if current.right:
  28. stack.append(current.right)
  29. stack.append(current)
  30. current = current.left
  31.  
  32. node = stack.pop()
  33.  
  34. # for current root, its right children havenโ€™t be handled
  35. # then handle right children first and then current root
  36. # by popping right children out and pushing current root back
  37. if len(stack) and node.right == stack[-1]:
  38. current = stack.pop()
  39. stack.append(node)
  40. else:
  41. result.append(node.val)
  42.  
  43. return result
Add Comment
Please, Sign In to add comment