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 theroot of the N-ary tree.
Custom testing:
An N-ary tree can be serialized as represented in its level order traversal where each group of children is separated by the null
value (see examples).
For example, the above tree is serialized as
[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
.
The testing will be done in the following way:
- The input data should be provided as a serialization of the tree.
- The driver code will construct the tree from the serialized input data and put each
Node
object into an array in an arbitrary order. - The driver code will pass the array to
findRoot
, and your function should find and return the rootNode
object in the array. - The driver code will take the returned
Node
object and serialize it. If the serialized value and the input data are the same , the test passes.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
- The total number of nodes is between
[1, 5 * 10^4]
. - Each node has a unique value.
Follow up:
- Could you solve this problem in constant space complexity with a linear time algorithm?
Solution
Method 1 – Bit Manipulation (XOR All Node Values)
Intuition
Every node except the root appears as a child of some node. If we XOR all node values and all child values, the result will be the root’s value, since all other values cancel out.
Approach
- Initialize a variable
xor_val
to 0. - For each node in the list:
- XOR
xor_val
with the node’s value. - For each child, XOR
xor_val
with the child’s value.
- XOR
- After the loop,
xor_val
will be the value of the root node. - Iterate again to find and return the node with value
xor_val
.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the number of nodes, since we visit each node and child once. - 🧺 Space complexity:
O(1)
, since we use only a few variables (excluding input/output).