[LeetCode] Find Root of N-Ary Tree

1506. Find Root of N-Ary Tree

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.

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:

  1. The input data should be provided as a serialization of the tree.
  2. The driver code will construct the tree from the serialized input data and put each Node object into an array in an arbitrary order.
  3. The driver code will pass the array to findRoot, and your function should find and return the root Node object in the array.
  4. 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.
  • Time : O(n)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;

Node() {}

Node(int _val) {
val = _val;
}

Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/

class Solution {
public:
Node* findRoot(vector<Node*> tree) {
unordered_set<int> childs;
for(auto node : tree) {
for(auto child : node->children) {
childs.insert(child->val);
}
}
for(auto node : tree) {
if(childs.count(node->val)) continue;
return node;
}
return NULL;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/14/PS/LeetCode/find-root-of-n-ary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.