forked from prabhupant/python-ds
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtop_view.py
More file actions
52 lines (38 loc) · 960 Bytes
/
top_view.py
File metadata and controls
52 lines (38 loc) · 960 Bytes
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
"""
Print the top view of a binary tree
Almost like vertical traversal
"""
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.col = None
def top_view(root):
if not root:
return
queue = []
col = 0
d = {}
queue.append(root)
root.col = col
while queue:
root = queue.pop(0)
col = root.col
if col not in d:
d[col] = root.val
if root.left:
queue.append(root.left)
root.left.col = col - 1
if root.right:
queue.append(root.right)
root.right.col = col + 1
for i in sorted(d):
print(d[i], end=" ")
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.right = Node(4)
root.left.right.right = Node(5)
root.left.right.right.right = Node(6)
top_view(root)