Find Root of N-Ary Tree - Problem
Problem: You're given all the nodes of an N-ary tree as an array, but they're in random order! Your task is to find which node is the root.

๐ŸŒณ What makes this interesting? In a tree, every node except the root has exactly one parent. The root node is special - it's the only node that nobody points to.

Input: An array of Node objects where each node contains:
โ€ข val - unique integer value
โ€ข children - list of child nodes

Output: Return the root Node object

Key Insight: The root is the only node that never appears in any other node's children list!

Input & Output

example_1.py โ€” Simple Tree
$ Input: tree = [Node(1, [Node(3), Node(2)]), Node(3, [Node(5)]), Node(2), Node(5)]
โ€บ Output: Node(1)
๐Ÿ’ก Note: Node 1 is the only node that doesn't appear in anyone's children list. Nodes 2, 3, and 5 all appear as children of other nodes.
example_2.py โ€” Single Node
$ Input: tree = [Node(1)]
โ€บ Output: Node(1)
๐Ÿ’ก Note: With only one node, it must be the root since there are no children anywhere.
example_3.py โ€” Deeper Tree
$ Input: tree = [Node(1, [Node(2), Node(3)]), Node(2, [Node(4)]), Node(3), Node(4)]
โ€บ Output: Node(1)
๐Ÿ’ก Note: Node 1 is root. Node 2 and 3 are children of 1. Node 4 is child of 2. Only node 1 never appears as anyone's child.

Constraints

  • The total number of nodes is between [1, 5 * 104]
  • Each node has a unique value
  • The input is guaranteed to be a valid tree (exactly one root)
  • Follow up: Could you solve this with O(1) extra space?

Visualization

Tap to expand
ROOTABCDE๐Ÿ’ก Key InsightThe ROOT is the only node that never appears in anyone's children list!Hash Set Solution: Mark all children โ†’ Find unmarked node โ†’ That's your root!
Understanding the Visualization
1
Identify the pattern
In any tree, every node except root is someone's child
2
Mark all children
Use a hash set to efficiently track who has parents
3
Find the orphan
The node without a parent is your root!
Key Takeaway
๐ŸŽฏ Key Insight: In any tree structure, the root is unique because it's the only node that nobody points to!
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
42.0K Views
Medium Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen