-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinaryTreeVerticalOrderTraversal.py
75 lines (66 loc) · 1.65 KB
/
BinaryTreeVerticalOrderTraversal.py
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
'''
bfs level order traversal with hashtable - ac
use bfs, not dfs
3=0
/\
/ \
9=-1 20=1
/\
/ \
15=0 7=2
'''
import heapq
class Solution:
def verticalOrder(self, root: TreeNode) -> List[List[int]]:
if not root:
return []
queue = [(root,0)]
dic = {}
while queue:
currv,currk = queue.pop(0)
if currk not in dic:
dic[currk] = [currv.val]
else:
dic[currk].append(currv.val)
if currv.left:
queue.append((currv.left,currk-1))
if currv.right:
queue.append((currv.right,currk+1))
r = []
heap = []
for i in dic:
heapq.heappush(heap,(i,dic[i]))
while heap:
r.append(heapq.heappop(heap)[1])
return r
'''
failed dfs solution - nodes with lower depth comes first
import heapq
class Solution:
def verticalOrder(self, root: TreeNode) -> List[List[int]]:
dic = {}
def trav(root,k):
if not root:
return
if k not in dic:
dic[k] = [root.val]
else:
dic[k].append(root.val)
trav(root.left,k-1)
trav(root.right,k+1)
return
trav(root,0)
r = []
heap = []
for i in dic:
heapq.heappush(heap,(i,dic[i]))
while heap:
r.append(heapq.heappop(heap)[1])
return r
'''