Coding questions · Uber
Compute outer boundary of an N-ary tree
This question evaluates proficiency in tree data structures and algorithm design, focusing on traversal and boundary extraction in ordered N-ary trees while requiring time and space complexity analysis.
You are given the root of a rooted N-ary tree. Each node contains:
- An integer value.
- An ordered list of children from left to right (0 or more children).
Consider all nodes grouped by their depth (root at depth 0, its children at depth 1, etc.). For each depth d:
- Let L_d be the leftmost node at depth
d(the first node at that depth when scanning children from left to right). - Let R_d be the rightmost node at depth
d(the last node at that depth when scanning children from left to right).
We define the outer boundary path of the tree as the sequence of nodes you would "see" when walking around the outside of the tree, starting from the lowest leftmost node, going up to the root, then going down to the lowest rightmost node:
- Starting from the maximum depth D down to
0, takeL_D, L_{D-1}, ..., L_0(bottom-left up to the root). - Then from depth
1up toD, takeR_1, R_2, ..., R_D(top-right down to bottom-right), skippingR_dwhenR_dis the same node asL_dto avoid duplicates on levels with only one node.
Return the list of node values in this exact order.
Assume:
- Total number of nodes
nsatisfies1 <= n <= 10^5. - Tree height
hcan be up tonin the worst case.
Task: Design an efficient algorithm to compute and return this outer boundary path. Specify the time and space complexity of your approach.
Outer Boundary of an N-ary Tree
Constraints
- Children are ordered left to right
Examples
Example 1
Input: ({'val': 1, 'children': [{'val': 2, 'children': [{'val': 5}, {'val': 6}]}, {'val': 3}, {'val': 4, 'children': [{'val': 7}]}]},)
Output: [5, 2, 1, 4, 7]
Example 2
Input: ({'val': 1},)
Output: [1]
Hints
- Level-order traversal gives leftmost and rightmost node per depth.