-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0314-binary-tree-vertical-order-traversal.py
More file actions
40 lines (30 loc) · 1.08 KB
/
Copy path0314-binary-tree-vertical-order-traversal.py
File metadata and controls
40 lines (30 loc) · 1.08 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
# https://leetcode.com/problems/binary-tree-vertical-order-traversal/submissions/
from collections import 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 verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root: return []
q = deque()
cols = {}
minCol = float('inf')
# val, col
q.append([root, 0])
while q:
root, col = q.popleft()
if col in cols: cols[col].append(root.val)
else: cols[col] = [root.val]
minCol = min(minCol, col)
if root.left:
q.append([root.left, col-1])
if root.right:
q.append([root.right, col+1])
output = []
while minCol in cols:
output.append(cols[minCol])
minCol+=1
return output