|
1 | | -# Approach 1: BFS/DFS with Global Sorting |
| 1 | +# Approach 2: BFS with Partition Sorting |
2 | 2 |
|
3 | | -# Time: O(N log N) |
4 | | -# Space: O(N) |
5 | | - |
6 | | -# BFS |
7 | | - |
8 | | -from collections import deque, OrderedDict |
| 3 | +# Time: O(n log n) |
| 4 | +# Space: O(n) |
9 | 5 |
|
10 | 6 | # Definition for a binary tree node. |
11 | 7 | # class TreeNode: |
|
14 | 10 | # self.left = left |
15 | 11 | # self.right = right |
16 | 12 |
|
| 13 | +from collections import deque, defaultdict |
| 14 | + |
17 | 15 | class Solution: |
18 | 16 | def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]: |
19 | | - node_list = [] |
20 | | - |
21 | | - def BFS(root): |
22 | | - queue = deque([(root, 0, 0)]) |
23 | | - |
24 | | - while queue: |
25 | | - node, row, col = queue.popleft() |
26 | | - if node is not None: |
27 | | - node_list.append((col, row, node.val)) |
28 | | - queue.append((node.left, row + 1, col - 1)) |
29 | | - queue.append((node.right, row + 1, col + 1)) |
30 | | - |
31 | | - BFS(root) |
32 | | - |
33 | | - node_list.sort() |
34 | | - |
35 | | - result = OrderedDict() |
36 | | - for col, row, value in node_list: |
37 | | - if col in result: |
38 | | - result[col].append(value) |
39 | | - else: |
40 | | - result[col] = [value] |
41 | | - |
42 | | - |
43 | | - return result.values() |
44 | | - |
| 17 | + if root is None: |
| 18 | + return [] |
| 19 | + |
| 20 | + columnTable = defaultdict(list) |
| 21 | + min_column = max_column = 0 |
| 22 | + |
| 23 | + queue = deque([(root, 0, 0)]) |
| 24 | + |
| 25 | + while queue: |
| 26 | + node, row, column = queue.popleft() |
| 27 | + if node is not None: |
| 28 | + columnTable[column].append((row, node.val)) |
| 29 | + min_column = min(min_column, column) |
| 30 | + max_column = max(max_column, column) |
| 31 | + |
| 32 | + queue.append((node.left, row + 1, column - 1)) |
| 33 | + queue.append((node.right, row + 1, column + 1)) |
| 34 | + |
| 35 | + result = [] |
| 36 | + for col in range(min_column, max_column + 1): |
| 37 | + result.append([val for row, val in sorted(columnTable[col])]) |
| 38 | + |
| 39 | + return result |
0 commit comments