Top View of BT

Pattern: Views and boundaries

medium

Give each node a column (left child -1, right child +1). The top view shows, for each column, the first node met in level order, which is the highest one. Read the columns from left to right.

The problem

Return the nodes visible from above the tree, from the leftmost column to the rightmost. In each column the highest node is visible; if two are equally high, the one met first in level order (the left one). [1, 2, 3, 4, 5, 6, 7] gives [4, 2, 1, 3, 7]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • How can you tell which nodes are in the same vertical line?
  • Which node of a column is seen from above?
  • Why does depth-first search make this harder?

Hints

    Brute force, and why it fails

    Depth-first with (column, depth), keeping the shallowest per column: also works with care.

    The key insight

    In level order, the first node met in each column is the highest, so a map that only keeps the first value gives the view.

    Dry run

    columns-2..2

    Tree [1, 2, 3, 4, 5, 6, 7]. Columns: 4 at -2, 2 at -1, 1, 5 and 6 at 0, 3 at 1, 7 at 2.

    Step 1 of 3

    The plan

    queue = [(root, 0)]; seen = ordered map
    while queue: (n, c) = pop front; if c not in seen: seen[c] = n.val; push children with c - 1, c + 1
    return seen values by column
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    BFS plus an ordered map of columns (a hash map and a min/max column also make it O(n)).

    Edge cases

    • Empty tree.
    • A chain to the left: every node is visible.
    • Two nodes in a column at the same depth.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> topView(TreeNode root) {
            TreeMap<Integer, Integer> seen = new TreeMap<>();   // column -> the value this view shows
            Queue<Object[]> q = new ArrayDeque<>();             // {node, column}, in level order
            if (root != null) q.add(new Object[]{root, 0});
            while (!q.isEmpty()) {
                Object[] item = q.poll();
                TreeNode node = (TreeNode) item[0];
                int col = (Integer) item[1];
                seen.putIfAbsent(col, node.val);              // the first node met in each column is on top
                if (node.left != null) q.add(new Object[]{node.left, col - 1});
                if (node.right != null) q.add(new Object[]{node.right, col + 1});
            }
            return new ArrayList<>(seen.values());              // columns from left to right
        }
    }

    C++

    class Solution {
    public:
        vector<int> topView(TreeNode* root) {
            map<int, int> seen;                                 // column -> the value this view shows
            queue<pair<TreeNode*, int>> q;                      // {node, column}, in level order
            if (root != NULL) q.push(make_pair(root, 0));
            while (!q.empty()) {
                TreeNode* node = q.front().first;
                int col = q.front().second;
                q.pop();
                if (!seen.count(col)) seen[col] = node->val;   // the first node met in each column is on top
                if (node->left != NULL) q.push(make_pair(node->left, col - 1));
                if (node->right != NULL) q.push(make_pair(node->right, col + 1));
            }
            vector<int> out;
            for (map<int, int>::iterator it = seen.begin(); it != seen.end(); ++it) out.push_back(it->second);   // left to right
            return out;
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def topView(self, root) -> list[int]:
            seen = {}                               # column -> the value this view shows
            q = deque([(root, 0)] if root else [])  # (node, column), in level order
            while q:
                node, col = q.popleft()
                seen.setdefault(col, node.val)  # the first node met in each column is on top
                if node.left:
                    q.append((node.left, col - 1))
                if node.right:
                    q.append((node.right, col + 1))
            return [seen[c] for c in sorted(seen)]  # columns from left to right

    Common mistakes

    • Using depth-first order without depths.
    • Overwriting a column's value.

    Similar problems