-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathvertical-order-traversal-of-a-binary-tree.py
More file actions
46 lines (32 loc) · 1.11 KB
/
vertical-order-traversal-of-a-binary-tree.py
File metadata and controls
46 lines (32 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import heapq
from typing import List, Tuple
from collections import defaultdict, deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
def dfs(
node: TreeNode, row: int, col: int, heap: List[Tuple[int, int, int]]
) -> None:
heapq.heappush(heap, (col, row, node.val))
if node.left:
dfs(node.left, row + 1, col - 1, heap)
if node.right:
dfs(node.right, row + 1, col + 1, heap)
if not root:
return []
heap: List[Tuple[int, int, int]] = []
dfs(root, 0, 0, heap)
result: List[List[int]] = []
col_prev = float("-inf") # row 1 does not exist
while heap:
col, row, val = heapq.heappop(heap)
if col != col_prev:
result.append([])
result[-1].append(val)
col_prev = col
return result