Sponsored
Sponsored
The idea is to identify the type of each node by examining the parent-child relationship. Specifically, to identify:
Steps:
Time Complexity: O(n), where n is the number of nodes, as we traverse through the list of nodes usually once or twice.
Space Complexity: O(n), used by the children count array and the result array.
1#include <iostream>
2#include <vector>
3#include <unordered_map>
4
5using namespace std;
6
7struct Node {
8 int id, p_id;
9};
10
11void classifyNodes(vector<Node>& nodes) {
12 unordered_map<int, int> childCount;
13 unordered_map<int, string> types;
14
15 for (const auto& node : nodes) {
16 if (node.p_id != -1) {
17 childCount[node.p_id]++;
18 }
19 types[node.id] = "Leaf";
20 }
21
22 for (const auto& node : nodes) {
23 if (node.p_id == -1) {
24 types[node.id] = "Root";
25 } else if (childCount[node.id]) {
26 types[node.id] = "Inner";
27 }
28 }
29
30 for (const auto& node : nodes) {
31 cout << node.id << " " << types[node.id] << endl;
32 }
33}
34
35int main() {
36 vector<Node> nodes = {{1, -1}, {2, 1}, {3, 1}, {4, 2}, {5, 2}};
37 classifyNodes(nodes);
38 return 0;
39}
The C++ solution uses a vector to store the nodes and two unordered maps to record the child counts and types. By iterating over each node, we establish the type based on having children or being a root node, and print the results accordingly.
This approach centers around identifying nodes type by tracking parent relationships directly:
Steps:
Time Complexity: O(n)
Space Complexity: O(n)
using System.Collections.Generic;
public class Node {
public int Id, PId;
public Node(int id, int pId) { Id = id; PId = pId; }
}
public class TreeNode {
public static void ClassifyNodes(List<Node> nodes) {
var isChild = new HashSet<int>();
foreach (var node in nodes) {
if (node.PId != -1) isChild.Add(node.PId);
}
foreach (var node in nodes) {
if (node.PId == -1) {
Console.WriteLine(node.Id + " Root");
} else if (isChild.Contains(node.Id)) {
Console.WriteLine(node.Id + " Inner");
} else {
Console.WriteLine(node.Id + " Leaf");
}
}
}
public static void Main() {
List<Node> nodes = new List<Node> {
new Node(1, -1), new Node(2, 1), new Node(3, 1), new Node(4, 2), new Node(5, 2)
};
ClassifyNodes(nodes);
}
}
C# utilizes a HashSet to efficiently maintain a transaction log of child nodes, making subsequent checks for node class straightforward, leading to an improved read operation structure.