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
โข
โข
Output: Return the root
Key Insight: The root is the only node that never appears in any other node's children list!
๐ณ 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 nodesOutput: Return the root
Node objectKey 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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code