#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// Tree node structure
typedef struct Node {
int val;
struct Node** children;
int child_count;
} Node;
// Global variable to track max path sum
int max_path_sum = INT_MIN;
// Function to create a new node
Node* newNode(int val) {
Node* node = (Node*)malloc(sizeof(Node));
node->val = val;
node->children = NULL;
node->child_count = 0;
return node;
}
// Add child to a node
void addChild(Node* parent, Node* child) {
parent->child_count++;
parent->children = (Node**)realloc(parent->children, parent->child_count * sizeof(Node*));
parent->children[parent->child_count - 1] = child;
}
// DFS function returns max single path sum from this node down
int dfs(Node* node) {
if (!node) return 0;
int max1 = 0, max2 = 0; // top two max child paths
// Check all children
for (int i = 0; i < node->child_count; i++) {
int child_sum = dfs(node->children[i]);
if (child_sum > max1) {
max2 = max1;
max1 = child_sum;
} else if (child_sum > max2) {
max2 = child_sum;
}
}
// Max single path from this node
int max_single = node->val + (max1 > 0 ? max1 : 0);
// Max path through this node (could connect two children)
int max_top = node->val + (max1 > 0 ? max1 : 0) + (max2 > 0 ? max2 : 0);
if (max_top > max_path_sum) {
max_path_sum = max_top;
}
return max_single;
}
int main() {
// Build tree from dry run example
Node* n1 = newNode(10);
Node* n2 = newNode(2);
Node* n3 = newNode(10);
Node* n4 = newNode(20);
Node* n5 = newNode(1);
addChild(n1, n2);
addChild(n1, n3);
addChild(n2, n4);
addChild(n2, n5);
dfs(n1);
printf("Maximum path sum = %d\n", max_path_sum);
// Free memory omitted for brevity
return 0;
}for (int i = 0; i < node->child_count; i++) {
Traverse all children to find their max single path sums
int child_sum = dfs(node->children[i]);
Recursively get max single path sum from child
if (child_sum > max1) { max2 = max1; max1 = child_sum; } else if (child_sum > max2) { max2 = child_sum; }
Keep track of top two max child paths for possible path through node
int max_single = node->val + (max1 > 0 ? max1 : 0);
Max single path from node includes node value plus best child path if positive
int max_top = node->val + (max1 > 0 ? max1 : 0) + (max2 > 0 ? max2 : 0);
Max path through node can connect two best child paths plus node value
if (max_top > max_path_sum) { max_path_sum = max_top; }
Update global max path sum if current path is better
Return max single path sum for parent's calculation