Top View of Binary Tree Solved Using BFS and Horizontal Distance Tracking
The top view of a binary tree returns the first visible node at each horizontal distance (HD) when the tree is viewed from above. Using breadth-first search (BFS), nodes are processed level by level, ensuring the first node encountered at any given HD is always the topmost one. Each node is assigned an HD — root at 0, left child at HD−1, and right child at HD+1 — and stored in a TreeMap only if that HD has not been seen before. This approach avoids storing redundant nodes and yields a sorted left-to-right result by traversing the TreeMap. The solution runs in O(N log N) time and O(N) space, with the logarithmic factor arising from TreeMap insertions.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in