757. Dashboard previews: right, left and bottom views of a decision tree
Your ML dashboard draws trained decision trees, and big trees do not fit on a phone screen. The compact preview shows only the nodes you would see if you looked at the tree from one side, or from below, like a silhouette. Product wants three previews: right, left and bottom.
Write tree_view(values, side).
- values is the tree in level order with None for a missing child: each non-None node takes the next two entries as its left and right child. This is the format trees are usually stored in (LeetCode uses the same one). Trailing entries can be missing.
- side is 'right', 'left' or 'bottom'.
Views:
- 'right': the last node of each depth, top to bottom.
- 'left': the first node of each depth, top to bottom.
- 'bottom': give each node a column (root 0, left child column - 1, right child column + 1). For each column from left to right, return the node seen last in breadth-first order: deeper wins, and on the same depth the one further right wins. A depth-first walk visits nodes in the wrong order for this rule, so use a queue.
Constraints: up to 10,000 nodes, and a tree can be a long chain thousands of levels deep, so avoid recursion. An empty tree (values = []) returns [] for every side.
def tree_view(values, side)Example 1
Input: values = [1, 2, 3, None, 5, None, 4]. tree_view(values, 'right')
Output: [1, 3, 4] and tree_view(values, 'left') returns [1, 2, 5]
Example 2
Input: tree_view(values, 'bottom')
Output: [2, 5, 3, 4]: node 5 is the right child of 2
Explanation: So it sits in column 0 under the root and hides it.
Constraints
- Up to 100,000 nodes.
- Node values are integers.
Hint 1
Decode the list with a queue.
Hint 2
Record nodes per depth for side views.
Hint 3
Overwrite per column in BFS order for the bottom view.
Common mistakes
- Treating None entries as nodes that take children.
- Using depth first search for the bottom view, which visits nodes in the wrong order for tie breaking.
- Recursion that hits Python's depth limit on a long chain.
Understand the idea
Most tree view questions are breadth first search plus one extra piece of state. Depth gives side views; a horizontal column gives top and bottom views. When an interviewer changes the rule (which node wins a column, which side you look from), the traversal stays the same and only the update rule changes, so say the rule out loud before coding.