|
| 1 | +from collections import deque |
| 2 | + |
| 3 | +# Definition for a binary tree node |
| 4 | +class TreeNode: |
| 5 | + def __init__(self, val=0, left=None, right=None): |
| 6 | + self.data = val |
| 7 | + self.left = left |
| 8 | + self.right = right |
| 9 | + |
| 10 | +class Solution: |
| 11 | + # Function to return the top view of the binary tree |
| 12 | + def topView(self, root): |
| 13 | + # List to store the result |
| 14 | + ans = [] |
| 15 | + |
| 16 | + # Check if the tree is empty |
| 17 | + if root is None: |
| 18 | + return ans |
| 19 | + |
| 20 | + # Dictionary to store the top view nodes based on their vertical positions |
| 21 | + mpp = {} |
| 22 | + |
| 23 | + # Queue for BFS traversal, each element is a pair containing node and its vertical position |
| 24 | + q = deque([(root, 0)]) |
| 25 | + |
| 26 | + # BFS traversal |
| 27 | + while q: |
| 28 | + # Retrieve the node and its vertical position from the front of the queue |
| 29 | + node, line = q.popleft() |
| 30 | + |
| 31 | + # If the vertical position is not already in the map, add the node's data to the map |
| 32 | + if line not in mpp: |
| 33 | + mpp[line] = node.data |
| 34 | + |
| 35 | + # Process left child |
| 36 | + if node.left: |
| 37 | + # Push the left child with a decreased vertical position into the queue |
| 38 | + q.append((node.left, line - 1)) |
| 39 | + |
| 40 | + # Process right child |
| 41 | + if node.right: |
| 42 | + # Push the right child with an increased vertical position into the queue |
| 43 | + q.append((node.right, line + 1)) |
| 44 | + |
| 45 | + # Transfer values from the map to the result list |
| 46 | + for key in sorted(mpp.keys()): |
| 47 | + ans.append(mpp[key]) |
| 48 | + |
| 49 | + return ans |
| 50 | + |
| 51 | +# Creating a sample binary tree |
| 52 | +root = TreeNode(1) |
| 53 | +root.left = TreeNode(2) |
| 54 | +root.left.left = TreeNode(4) |
| 55 | +root.left.right = TreeNode(10) |
| 56 | +root.left.left.right = TreeNode(5) |
| 57 | +root.left.left.right.right = TreeNode(6) |
| 58 | +root.right = TreeNode(3) |
| 59 | +root.right.right = TreeNode(10) |
| 60 | +root.right.left = TreeNode(9) |
| 61 | + |
| 62 | +solution = Solution() |
| 63 | + |
| 64 | +# Get the top view traversal |
| 65 | +top_view = solution.topView(root) |
| 66 | + |
| 67 | +# Print the result |
| 68 | +print("Top View Traversal:") |
| 69 | +for node in top_view: |
| 70 | + print(node, end=" ") |
0 commit comments