Outer boundary of an N-ary tree
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Uber's technical phone screen, last asked Oct 2025. It tests trees, bfs and traversal.
You get the root of an N-ary tree whose children are ordered from left to right. Group the nodes by depth, with the root at depth 0. At each depth, the leftmost node is the first one at that depth scanning left to right, and the rightmost node is the last. Return the tree's outer boundary: the leftmost nodes from the deepest level up to the root, then the rightmost nodes from depth 1 down to the deepest level. At a depth with a single node, that node appears once.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
outer_boundary(root: Node) -> list[int]—Nodehasval: intandchildren: list[Node]. - With
L_dandR_dthe leftmost and rightmost nodes at depthdandDthe deepest depth, returnL_D, ..., L_1, L_0, R_1, ..., R_D, skippingR_dwhen it is the same node asL_d.
Example
1
/ | \
2 3 4
/ \ |
5 6 7
outer_boundary(root) -> [5, 2, 1, 4, 7]
1
/ \
2 3
| / \
4 5 6
|
8
outer_boundary(root) -> [8, 4, 2, 1, 3, 6] # depth 3 holds only 8, so it appears once
Constraints
-
1 <= n <= 10^5; the tree can be a single chain of heightn.
Clarifying questions
- Is "leftmost" per depth, or the path you would walk along the outside edge of the drawing?
- At a depth with one node, is it listed once? (Yes.)
- Should leaves in the middle of the bottom be included, as in a binary tree's boundary? (No, only the leftmost and rightmost per depth.)
- Values or node references in the output?
What a strong answer covers
- Agreeing on the exact definition and the output for the examples before coding.
- A level-order traversal with a queue that records the first and last node of each level, O(n) time and O(width) space.
- Comparing node identity, not values, when deciding whether
L_dandR_dare the same. - Building the left part in reverse and appending the right part.
- No recursion, so a chain of 10^5 nodes is fine.
- Tests: a single node, a chain, a tree whose deepest level has one node, a wide shallow tree.
Follow-ups
- Return the classic boundary instead: left edge, then all leaves left to right, then the right edge bottom-up.
- Do it with a DFS that tracks the first and last node seen at each depth.
- Return the boundary of a binary tree in the same per-depth sense.
Where it's asked
- Uber · Technical phone screen · Last asked Oct 202560 min · One medium problem with a follow-up, or two short ones; sometimes object-oriented design
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
