You are given the root of a rooted N-ary tree. Each node contains:
Consider all nodes grouped by their depth (root at depth 0, its children at depth 1, etc.). For each depth d:
d
(the first node at that depth when scanning children from left to right).
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:
0
, take
L_D, L_{D-1}, ..., L_0
(bottom-left up to the root).
1
up to
D
, take
R_1, R_2, ..., R_D
(top-right down to bottom-right),
skipping
R_d
when
R_d
is the same node as
L_d
to avoid duplicates on levels with only one node.
Return the list of node values in this exact order.
Assume:
n
satisfies
1 <= n <= 10^5
.
h
can be up to
n
in 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.