Top View of a Binary Tree - Iterative Approach
Visualization Player
Solution
Algorithm Steps
Code
Python
Java
JavaScript
C
C++
C#
Kotlin
Swift
Go
Php
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def topView(root):
if not root:
return []
from collections import deque
queue = deque([(root, 0)])
hd_map = {}
while queue:
node, hd = queue.popleft()
if hd not in hd_map:
hd_map[hd] = node.val
if node.left:
queue.append((node.left, hd - 1))
if node.right:
queue.append((node.right, hd + 1))
return [hd_map[hd] for hd in sorted(hd_map)]
# Example usage:
if __name__ == '__main__':
# Construct binary tree:
# 1
# / \
# 2 3
# / \ \
# 4 5 6
root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, None, TreeNode(6)))
print(topView(root))