DEV Community

Cover image for Day 6 of 100 days dsa coding challenge
Manasi Patil
Manasi Patil

Posted on

Day 6 of 100 days dsa coding challenge

Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! πŸ’»πŸ”₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! πŸš€

100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney

Problem:

https://www.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1

Bottom View of Binary Tree

Difficulty: Medium Accuracy: 54.18%

You are given the root of a binary tree, and your task is to return its bottom view. The bottom view of a binary tree is the set of nodes visible when the tree is viewed from the bottom.
Note: If there are multiple bottom-most nodes for a horizontal distance from the root, then the latter one in the level order traversal is considered.
Examples :
Input: root = [1, 2, 3, 4, 5, N, 6]

Output: [4, 2, 5, 3, 6]
Explanation: The Green nodes represent the bottom view of below binary tree.

Input: root = [20, 8, 22, 5, 3, 4, 25, N, N, 10, 14, N, N, 28, N]

Output: [5, 10, 4, 28, 25]
Explanation: The Green nodes represent the bottom view of below binary tree.

Constraints:
1 ≀ number of nodes ≀ 105
1 ≀ node->data ≀ 105

Solution:
from collections import deque

class Solution:
def bottomView(self, root):
if not root:
return []
q = deque([(root, 0)])
hd_map = {}
while q:
node, hd = q.popleft()
hd_map[hd] = node.data
if node.left:
q.append((node.left, hd - 1))
if node.right:
q.append((node.right, hd + 1))
return [hd_map[x] for x in sorted(hd_map.keys())]

Top comments (0)