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
Find Root of N-Ary Tree INPUT Array of N-ary Tree Nodes Node 1: val=1 children: [3, 2, 4] Node 2: val=3, children: [] Node 3: val=2, children: [] Node 4: val=4, children: [] Tree Structure: 1 3 2 4 ALGORITHM STEPS 1 Create HashSet Store all node values allNodes = {1, 3, 2, 4} Sum = 1+3+2+4 = 10 2 Iterate Children Remove from hash/sum Children: [3, 2, 4] Sum = 10-3-2-4 = 1 3 Remaining = Root Only root has no parent Remaining value = 1 Root node found! 4 Return Root Find node with val=1 FINAL RESULT Root Node Identified 1 ROOT 3 2 4 Output: Node with val = 1 children: [3, 2, 4] OK - Root Found! Verification: Node 1 is NOT a child of any other node Key Insight: The root is the ONLY node that never appears as a child of any other node. Using a HashSet: Add all node values, then remove all children values. The remaining value is the root! Alternative: Sum all values, subtract all children values. Remaining = root value. Time: O(n), Space: O(1) TutorialsPoint - Find Root of N-Ary Tree | Hash Approach
Asked in
Google 25 Amazon 20 Facebook 15 Microsoft 12
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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