
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Top View of a Binary Tree in Python
Suppose we have a binary tree, we have to find the top view of the tree, they will be sorted left−to−right.
So, if the input is like image, then the output will be [3, 5, 8, 6, 9], as 3 is above 2 and 5 is above 7 so they are not visible.
To solve this, we will follow these steps −
view := a new empty map
q := a double ended queue
insert pair (root, 0) at the end of q
start := inf, end := −inf
-
while q is not empty, do
(node, coord) := left element of q, then remove left element of q
start := minimum of start and coord
end := maximum of end and coord
-
if coord is not in view, then
view[coord] := value of node
-
if left of node is not null, then
insert (left of node, coord − 1) at the end of q
-
if right of node is not null, then
insert (right of node, coord + 1) at the end of q
res := a new list
-
for i in range start to end, do
-
if i is in view, then
insert view[i] at the end of res
-
return res
Let us see the following implementation to get better understanding −
Example
from collections import deque class TreeNode: def __init__(self, data, left = None, right = None): self.val = data self.left = left self.right = right class Solution: def solve(self, root): view = {} q = deque() q.append((root, 0)) start = float("inf") end = float("-inf") while q: node, coord = q.popleft() start = min(start, coord) end = max(end, coord) if coord not in view: view[coord] = node.val if node.left: q.append((node.left, coord - 1)) if node.right: q.append((node.right, coord + 1)) res = [] for i in range(start, end + 1): if i in view: res.append(view[i]) return res ob = Solution() root = TreeNode(5) root.left = TreeNode(3) root.right = TreeNode(8) root.right.left = TreeNode(7) root.right.right = TreeNode(6) root.right.left.left = TreeNode(2) root.right.right.right = TreeNode(9) print(ob.solve(root))
Input
root = TreeNode(5) root.left = TreeNode(3) root.right = TreeNode(8) root.right.left = TreeNode(7) root.right.right = TreeNode(6) root.right.left.left = TreeNode(2) root.right.right.right = TreeNode(9)
Output
[3, 5, 8, 6, 9]