|
| 1 | +# 94. Binary Tree Inorder Traversal |
| 2 | + |
| 3 | +## Recursive solution |
| 4 | +- Runtime: O(N) |
| 5 | +- Space: O(1) |
| 6 | +- N = Number of elements in tree |
| 7 | + |
| 8 | +Make sure you understand the recursive solution first before attempting the iterative one. |
| 9 | +The main point is to understand the recursive call and how it backtracks to the previous call when it reaches the base case. |
| 10 | + |
| 11 | +``` |
| 12 | +class Solution: |
| 13 | + def inorderTraversal(self, root: TreeNode) -> List[int]: |
| 14 | + def inorder_traversal_helper(root, result): |
| 15 | + if root is None: |
| 16 | + return |
| 17 | + inorder_traversal_helper(root.left, result) |
| 18 | + result.append(root.val) |
| 19 | + inorder_traversal_helper(root.right, result) |
| 20 | + |
| 21 | + result = list() |
| 22 | + inorder_traversal_helper(root, result) |
| 23 | + return result |
| 24 | +``` |
| 25 | + |
| 26 | +## Iterative solution |
| 27 | +- Runtime: O(N) |
| 28 | +- Space: O(1) |
| 29 | +- N = Number of elements in tree |
| 30 | + |
| 31 | +To fully understand this implementation, I recommend you draw this out step by step. |
| 32 | +Iterative inorder traversal can be confusing, no amount of words can help describe its inner workings. |
| 33 | +Don't try to memorize this, understand it. |
| 34 | + |
| 35 | +A good starting point for converting a recursive binary tree solution into an iterative one is to start with a stack, current node variable and a while loop. |
| 36 | +Those should be your starting ingredients. |
| 37 | + |
| 38 | +``` |
| 39 | +class Solution: |
| 40 | + def inorderTraversal(self, root: TreeNode) -> List[int]: |
| 41 | + stack, result = list(), list() |
| 42 | + curr_node = root |
| 43 | + while True: |
| 44 | + if curr_node is not None: |
| 45 | + stack.append(curr_node) |
| 46 | + curr_node = curr_node.left |
| 47 | + elif len(stack) > 0: |
| 48 | + curr_node = stack.pop() |
| 49 | + result.append(curr_node.val) |
| 50 | + curr_node = curr_node.right |
| 51 | + else: |
| 52 | + break |
| 53 | + return result |
| 54 | +``` |
0 commit comments