|
| 1 | +''' |
| 2 | +# Leetcode 102. Binary Tree Level Order Traversal |
| 3 | +
|
| 4 | +do level order traversal |
| 5 | +
|
| 6 | +``` |
| 7 | +💡 why use BFS?: |
| 8 | +BFS is the recommended approach, because it aligns with the problem's concept of processing the binary tree level by level and avoids issues related to recursion depth, making the solution both cleaner and more reliable. |
| 9 | +
|
| 10 | +- DFS doesn't naturally support level-by-level traversal, so we need an extra variable like "dep" (depth). |
| 11 | +- BFS is naturally designed for level traversal, making it a better fit for the problem. |
| 12 | +- additionally, BFS can avoid potential stack overflow. |
| 13 | +``` |
| 14 | +
|
| 15 | +## A. BFS |
| 16 | +
|
| 17 | +### re-structuring the tree into a queue: |
| 18 | +- use the queue for traverse the binary tree by level. |
| 19 | +
|
| 20 | +### level traversal: |
| 21 | +- pop the leftmost node |
| 22 | +- append the node's value to current level's array |
| 23 | +- enqueue the left and right children to queue |
| 24 | +- can only process nodes at the current level, because of level_size. |
| 25 | +
|
| 26 | +## B. DFS |
| 27 | +- travase with a dep parameter => dp(node, dep) |
| 28 | +- store the traversal result |
| 29 | +''' |
| 30 | +class Solution: |
| 31 | + ''' |
| 32 | + A. BFS |
| 33 | + TC: O(n) |
| 34 | + SC: O(n) |
| 35 | + ''' |
| 36 | + def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: |
| 37 | + if not root: |
| 38 | + return [] |
| 39 | + |
| 40 | + result = [] # SC: O(n) |
| 41 | + queue = deque([root]) # SC: O(n) |
| 42 | + |
| 43 | + while queue: # TC: O(n) |
| 44 | + level_size = len(queue) |
| 45 | + level = [] |
| 46 | + |
| 47 | + for _ in range(level_size): |
| 48 | + node = queue.popleft() |
| 49 | + level.append(node.val) |
| 50 | + |
| 51 | + if node.left: |
| 52 | + queue.append(node.left) |
| 53 | + if node.right: |
| 54 | + queue.append(node.right) |
| 55 | + |
| 56 | + result.append(level) |
| 57 | + |
| 58 | + return result |
| 59 | + |
| 60 | + ''' |
| 61 | + B. DFS |
| 62 | + TC: O(n) |
| 63 | + SC: O(n) |
| 64 | + ''' |
| 65 | + def levelOrderDP(self, root: Optional[TreeNode]) -> List[List[int]]: |
| 66 | + result = [] # SC: O(n) |
| 67 | + |
| 68 | + def dp(node, dep): |
| 69 | + if node is None: |
| 70 | + return |
| 71 | + |
| 72 | + if len(result) <= dep: |
| 73 | + result.append([]) |
| 74 | + |
| 75 | + result[dep].append(node.val) |
| 76 | + |
| 77 | + dp(node.left, dep + 1) |
| 78 | + dp(node.right, dep + 1) |
| 79 | + |
| 80 | + dp(root, 0) # TC: O(n) call stack |
| 81 | + |
| 82 | + return result |
0 commit comments