File tree Expand file tree Collapse file tree
data_structures/binary_tree Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11from collections import deque
22
3+
34# Definition for a binary tree node
45class 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+
1012class 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
5255root = TreeNode (1 )
5356root .left = TreeNode (2 )
You can’t perform that action at this time.
0 commit comments