Skip to content

Commit e6e881d

Browse files
committed
1 parent ed17fbb commit e6e881d

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import heapq
2+
from typing import List, Tuple
3+
from collections import defaultdict, deque
4+
5+
6+
# Definition for a binary tree node.
7+
class TreeNode:
8+
def __init__(self, val=0, left=None, right=None):
9+
self.val = val
10+
self.left = left
11+
self.right = right
12+
13+
14+
class Solution:
15+
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
16+
def dfs(
17+
node: TreeNode, row: int, col: int, heap: List[Tuple[int, int, int]]
18+
) -> None:
19+
heapq.heappush(heap, (col, row, node.val))
20+
if node.left:
21+
dfs(node.left, row + 1, col - 1, heap)
22+
if node.right:
23+
dfs(node.right, row + 1, col + 1, heap)
24+
25+
if not root:
26+
return []
27+
28+
heap: List[Tuple[int, int, int]] = []
29+
30+
dfs(root, 0, 0, heap)
31+
32+
result: List[List[int]] = []
33+
34+
col_prev = float("-inf") # row 1 does not exist
35+
36+
while heap:
37+
col, row, val = heapq.heappop(heap)
38+
39+
if col != col_prev:
40+
result.append([])
41+
42+
result[-1].append(val)
43+
44+
col_prev = col
45+
46+
return result

0 commit comments

Comments
 (0)