Sponsored
Sponsored
This approach uses Depth First Search (DFS) to explore the tree and find the longest path with different adjacent characters. The idea is to recursively explore each node, keeping track of the longest path encountered. As you traverse, ensure that any subsequent node is only considered in the path if it has a different character from its parent.
Time Complexity: O(n).
Space Complexity: O(n) due to the storage of the children array.
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5int dfs(int node, char *s, int **children, int *children_count, int *max_length) {
6 int first_longest = 0, second_longest = 0;
7 for (int i = 0; i < children_count[node]; i++) {
8 int child = children[node][i];
9 int path_length = dfs(child, s, children, children_count, max_length);
10 if (s[node] != s[child]) {
11 if (path_length > first_longest) {
12 second_longest = first_longest;
13 first_longest = path_length;
14 }
15 else if (path_length > second_longest) {
16 second_longest = path_length;
17 }
18 }
19 }
20 *max_length = fmax(*max_length, first_longest + second_longest + 1);
21 return first_longest + 1;
22}
23
24int longestPath(int* parent, int parentSize, char * s) {
25 int n = parentSize;
26 int **children = (int **)malloc(n * sizeof(int *));
27 int *children_count = (int *)calloc(n, sizeof(int));
28 int max_length = 0;
29
30 for (int i = 0; i < n; i++) {
31 children[i] = (int *)malloc(n * sizeof(int));
32 }
33
34 for (int i = 1; i < n; i++) {
35 children[parent[i]][children_count[parent[i]]++] = i;
36 }
37
38 dfs(0, s, children, children_count, &max_length);
39
40 for (int i = 0; i < n; i++) {
41 free(children[i]);
42 }
43 free(children);
44 free(children_count);
45
46 return max_length;
47}
The code defines a DFS function that explores each node's children, calculates the longest path from its children nodes that have distinct characters compared to the node. It accumulates the longest paths and returns the overall result.
Instead of using recursion, consider using an iterative Breadth First Search (BFS) approach. In this scenario, you explore each node level by level, maintaining a similar mechanism for avoiding paths with identical adjacent characters.
This approach generally requires additional bookkeeping to manage the nodes and their path lengths, but it can be beneficial in scenarios where recursion depth potential is problematic or not desired.
Time Complexity: O(n^2) in this version due to lack of adjacency list optimization.
Space Complexity: O(n) related to queue usage.
In JavaScript, a queue-based BFS approach is implemented to iteratively consider paths. Path lengths are extended where node characters differ, and the maximum length found defines the weighted result.