1624. Reverse the Family Order

A genealogy chart is stored as an N-ary tree: each node holds a value and an ordered list of children, drawn from left to right. You want the chart as seen in a mirror.

Implement mirrorFamily(root), which modifies the tree in place by reversing the order of the children list of every node, at all depths, so the leftmost child becomes the rightmost one. Nothing is returned; the judge reads the tree back from root after the call. Do not create new nodes or change any value.

A leaf has an empty (or missing) children list and needs no action. The tree can be a chain of up to 500 levels, so prefer an explicit stack or queue over recursion. Target complexity: O(n) time, O(n) extra space.

Example 1

Input:
root = [1,null,3,2,4,null,5,6]
Output:
[1,null,4,2,3,null,null,null,6,5]
Explanation:

Root 1 has children 3, 2, 4 which become 4, 2, 3; node 3's children 5, 6 become 6, 5.

Example 2

Input:
root = [8,null,1,2,3]
Output:
[8,null,3,2,1]
Explanation:

The three children of the root are listed in reverse order.

Example 3

Input:
root = [4]
Output:
[4]
Explanation:

A single node has nothing to reverse.

Constraints

1 ≤ nodes ≤ 500

depth ≤ 500

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Graded
Your answer is read from root after your method returns.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…