Find Root of N-Ary Tree - Problem
You are given all the nodes of an N-ary tree as an array of Node objects, where each node has a unique value.
Return the root of the N-ary tree.
Note: The root is the only node that is not a child of any other node. All other nodes have exactly one parent.
Input & Output
Example 1 — Simple Tree
$
Input:
tree = [{"val":1,"children":[3,2,4]},{"val":3,"children":[]},{"val":2,"children":[]},{"val":4,"children":[]}]
›
Output:
[{"val":1,"children":[3,2,4]},{"val":3,"children":[]},{"val":2,"children":[]},{"val":4,"children":[]}]
💡 Note:
Node 1 has children [3,2,4]. Nodes 3, 2, 4 are children of node 1. Only node 1 is never a child of any other node, so it's the root.
Example 2 — Two Levels
$
Input:
tree = [{"val":1,"children":[2,3]},{"val":2,"children":[4,5]},{"val":3,"children":[]},{"val":4,"children":[]},{"val":5,"children":[]}]
›
Output:
[{"val":1,"children":[2,3]},{"val":2,"children":[4,5]},{"val":3,"children":[]},{"val":4,"children":[]},{"val":5,"children":[]}]
💡 Note:
Node 1 is the parent of nodes 2 and 3. Node 2 is the parent of nodes 4 and 5. Only node 1 has no parent, making it the root.
Example 3 — Single Node
$
Input:
tree = [{"val":1,"children":[]}]
›
Output:
[{"val":1,"children":[]}]
💡 Note:
Only one node exists with no children. This single node is the root by definition.
Constraints
- The total number of nodes is between [1, 5 * 104].
- Each node has a unique value.
- 0 <= Node.val <= 105
- The input is guaranteed to be a tree (no cycles).
- The input will always have exactly one root.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of nodes with their children relationships
2
Process
Find the node that never appears as a child
3
Output
Return the root node
Key Takeaway
🎯 Key Insight: The root is the only node that never appears as someone's child - track all children and find the missing one
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code