Skip to content

Commit 8c50d8a

Browse files
rockanitechyminati
authored andcommitted
Create Top_View_Of_Binary_Tree.py
Adding python file
1 parent df918c8 commit 8c50d8a

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

Top_View_Of_Binary_Tree.py

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
# Python3 program to print top
2+
# view of binary tree
3+
4+
# Binary Tree Node
5+
""" utility that allocates a newNode
6+
with the given key """
7+
8+
9+
class newNode:
10+
11+
# Construct to create a newNode
12+
def __init__(self, key):
13+
self.data = key
14+
self.left = None
15+
self.right = None
16+
self.hd = 0
17+
18+
# function should print the topView
19+
# of the binary tree
20+
21+
22+
def topview(root):
23+
24+
if(root == None):
25+
return
26+
q = []
27+
m = dict()
28+
hd = 0
29+
root.hd = hd
30+
31+
# push node and horizontal
32+
# distance to queue
33+
q.append(root)
34+
35+
while(len(q)):
36+
root = q[0]
37+
hd = root.hd
38+
39+
# count function returns 1 if the
40+
# container contains an element
41+
# whose key is equivalent to hd,
42+
# or returns zero otherwise.
43+
if hd not in m:
44+
m[hd] = root.data
45+
if(root.left):
46+
root.left.hd = hd - 1
47+
q.append(root.left)
48+
49+
if(root.right):
50+
root.right.hd = hd + 1
51+
q.append(root.right)
52+
53+
q.pop(0)
54+
for i in sorted(m):
55+
print(m[i], end="")
56+
57+
58+
# Driver Code
59+
if __name__ == '__main__':
60+
61+
""" Create following Binary Tree
62+
1
63+
/ \
64+
2 3
65+
\
66+
4
67+
\
68+
5
69+
\
70+
6
71+
"""
72+
root = newNode(1)
73+
root.left = newNode(2)
74+
root.right = newNode(3)
75+
root.left.right = newNode(4)
76+
root.left.right.right = newNode(5)
77+
root.left.right.right.right = newNode(6)
78+
print("Following are nodes in top",
79+
"view of Binary Tree")
80+
topview(root)
81+

0 commit comments

Comments
 (0)