forked from fineanmol/Hacktoberfest2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbottomView.py
More file actions
30 lines (24 loc) · 791 Bytes
/
bottomView.py
File metadata and controls
30 lines (24 loc) · 791 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
from collections import deque
# Definition for a binary tree node.
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
class Solution:
def bottomView(self, root):
if not root:
return []
# Queue stores pairs: (node, horizontal_distance)
q = deque([(root, 0)])
hd_map = {} # hd -> node value
while q:
node, hd = q.popleft()
# For bottom view, we overwrite previous values
hd_map[hd] = node.data
if node.left:
q.append((node.left, hd - 1))
if node.right:
q.append((node.right, hd + 1))
# Sort by horizontal distance
return [hd_map[k] for k in sorted(hd_map)]