|
| 1 | +# 145. Binary Tree Postorder Traversal |
| 2 | + |
| 3 | +## Recursive Solution |
| 4 | +- Runtime: O(N) |
| 5 | +- Space: O(N) |
| 6 | +- N = Number of nodes in tree |
| 7 | + |
| 8 | +The recusive solution is fairly easy. Most of the heavy lifting is abstracted away by the recursion call. |
| 9 | + |
| 10 | +``` |
| 11 | +class Solution: |
| 12 | + def postorderTraversal(self, root: TreeNode) -> List[int]: |
| 13 | + def postorder_traversal_helper(root, result): |
| 14 | + if root is None: |
| 15 | + return |
| 16 | + postorder_traversal_helper(root.left, result) |
| 17 | + postorder_traversal_helper(root.right, result) |
| 18 | + result.append(root.val) |
| 19 | + |
| 20 | + result = list() |
| 21 | + postorder_traversal_helper(root, result) |
| 22 | + return result |
| 23 | +``` |
| 24 | + |
| 25 | +## Iterative Solution |
| 26 | +- Runtime: O(N) |
| 27 | +- Space: O(N) |
| 28 | +- N = Number of nodes in tree |
| 29 | + |
| 30 | +The iterative solution for post order is fairly diffucult to come up with on your own. |
| 31 | +It requires two stacks. |
| 32 | +The first stack is used to traverse the tree but in the opposite direction, going to the right side first then visiting the left nodes. |
| 33 | +During the traversal, the 2nd stack will place the nodes in the reverse order or post-order when they are popped off the stack. |
| 34 | +I recommend drawing this out, as its important to understand the relationships and responsibilities. |
| 35 | + |
| 36 | +``` |
| 37 | +class Solution: |
| 38 | + def postorderTraversal(self, root: TreeNode) -> List[int]: |
| 39 | + if root is None: |
| 40 | + return [] |
| 41 | + stack1, stack2 = list([root]), list() |
| 42 | + result = list() |
| 43 | + while len(stack1) > 0: |
| 44 | + node = stack1.pop() |
| 45 | + stack2.append(node) |
| 46 | + if node.left is not None: |
| 47 | + stack1.append(node.left) |
| 48 | + if node.right is not None: |
| 49 | + stack1.append(node.right) |
| 50 | + while len(stack2) > 0: |
| 51 | + node = stack2.pop() |
| 52 | + result.append(node.val) # <-- Business logic goes here |
| 53 | + return result |
| 54 | +``` |
0 commit comments