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 <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5#define MAX_NODES 100
6
7typedef struct {
8 int id;
9 int p_id;
10} Node;
11
12typedef struct {
13 int id;
14 char type[10];
15} ResultNode;
16
17void classifyNodes(Node nodes[], int n, ResultNode result[]) {
18 int children[MAX_NODES] = {0};
19 int isRoot[MAX_NODES] = {0};
20
21 for (int i = 0; i < n; i++) {
22 if (nodes[i].p_id == -1) {
23 isRoot[nodes[i].id] = 1;
24 continue;
25 }
26 children[nodes[i].p_id]++;
27 }
28
29 for (int i = 0; i < n; i++) {
30 int id = nodes[i].id;
31 strcpy(result[i].type, "Leaf");
32 if (children[id] > 0) strcpy(result[i].type, "Inner");
33 if (isRoot[id]) strcpy(result[i].type, "Root");
34 result[i].id = id;
35 }
36}
37
38int main() {
39 Node nodes[] = {{1, -1}, {2, 1}, {3, 1}, {4, 2}, {5, 2}};
40 int n = 5;
41 ResultNode result[5];
42 classifyNodes(nodes, n, result);
43 for (int i = 0; i < n; i++) {
44 printf("%d %s\n", result[i].id, result[i].type);
45 }
46 return 0;
47}
The C solution defines a Node structure to store the id and p_id information. It uses an additional array to count the children of each node. By examining the relationship between p_id and id, we can easily determine the type of each node. Lastly, we set the type as 'Leaf', 'Inner', or 'Root' in the output list of ResultNode structures.
This approach centers around identifying nodes type by tracking parent relationships directly:
Steps:
Time Complexity: O(n)
Space Complexity: O(n)
1using 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.