Skip to content

Commit ab7252e

Browse files
Print Nodes in Bottom View of Binary Tree
1 parent a1d764f commit ab7252e

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,7 @@ Contains implementation of Tree data structure and some common questions and alg
158158

159159
| Topic/Question | Code File Name |
160160
|-----------------------------------|------------------|
161+
|Print Nodes in Bottom View of Binary Tree|Bottom_View.py|
161162
|Check if a binary tree is height balanced|Check_Balanced.py|
162163
|Given two binary trees, check if the first tree is subtree of the second one|Is_SubTree.py|
163164
|Find the Lowest Common Ancestor in a Binary Tree|Lowest_Common_Ancestor.py|

Tree/BinaryTree/Bottom_View.py

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Print Nodes in Bottom View of Binary Tree
2+
from collections import deque
3+
4+
5+
class Node:
6+
def __init__(self, data):
7+
self.data = data
8+
self.left = None
9+
self.right = None
10+
11+
12+
def bottom_view(root):
13+
if root is None:
14+
return
15+
16+
# make an empty queue for BFS
17+
q = deque()
18+
19+
# dict to store bottom view keys
20+
bottomview = {}
21+
22+
# append root in the queue with horizontal distance as 0
23+
q.append((root, 0))
24+
25+
while q:
26+
# get the element and horizontal distance
27+
elem, hd = q.popleft()
28+
29+
# update the last seen hd element
30+
bottomview[hd] = elem.data
31+
32+
# add left and right child in the queue with hd - 1 and hd + 1
33+
if elem.left is not None:
34+
q.append((elem.left, hd - 1))
35+
if elem.right is not None:
36+
q.append((elem.right, hd + 1))
37+
38+
# return the bottomview
39+
return bottomview
40+
41+
42+
if __name__ == '__main__':
43+
root = Node(20)
44+
root.left = Node(8)
45+
root.right = Node(22)
46+
root.left.left = Node(5)
47+
root.left.right = Node(3)
48+
root.right.left = Node(4)
49+
root.right.right = Node(25)
50+
root.left.right.left = Node(10)
51+
root.left.right.right = Node(14)
52+
53+
bottomview = bottom_view(root)
54+
55+
for i in sorted(bottomview):
56+
print(bottomview[i], end=' ')

0 commit comments

Comments
 (0)