Skip to content

Commit 7c2dd04

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 84ef8d0 commit 7c2dd04

1 file changed

Lines changed: 12 additions & 9 deletions

File tree

data_structures/binary_tree/top_view_of_binary_tree.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,56 @@
11
from collections import deque
22

3+
34
# Definition for a binary tree node
45
class TreeNode:
56
def __init__(self, val=0, left=None, right=None):
67
self.data = val
78
self.left = left
89
self.right = right
910

11+
1012
class Solution:
1113
# Function to return the top view of the binary tree
1214
def topView(self, root):
1315
# List to store the result
1416
ans = []
15-
17+
1618
# Check if the tree is empty
1719
if root is None:
1820
return ans
19-
21+
2022
# Dictionary to store the top view nodes based on their vertical positions
2123
mpp = {}
22-
24+
2325
# Queue for BFS traversal, each element is a pair containing node and its vertical position
2426
q = deque([(root, 0)])
25-
27+
2628
# BFS traversal
2729
while q:
2830
# Retrieve the node and its vertical position from the front of the queue
2931
node, line = q.popleft()
30-
32+
3133
# If the vertical position is not already in the map, add the node's data to the map
3234
if line not in mpp:
3335
mpp[line] = node.data
34-
36+
3537
# Process left child
3638
if node.left:
3739
# Push the left child with a decreased vertical position into the queue
3840
q.append((node.left, line - 1))
39-
41+
4042
# Process right child
4143
if node.right:
4244
# Push the right child with an increased vertical position into the queue
4345
q.append((node.right, line + 1))
44-
46+
4547
# Transfer values from the map to the result list
4648
for key in sorted(mpp.keys()):
4749
ans.append(mpp[key])
48-
50+
4951
return ans
5052

53+
5154
# Creating a sample binary tree
5255
root = TreeNode(1)
5356
root.left = TreeNode(2)

0 commit comments

Comments
 (0)