int main() { srand(time(NULL)); struct node *tree; int used[N] = {0}; int i = N - M; int path[M], max_path[M], side_path[M], max, j, c, cm; tree = createTree(M, used, &i); inorderTraversal(tree); printf("\n\n"); preorderTraversal(tree); printf("\n\n"); postorderTraversal(tree); printf("\n\n"); max = maxRootSumPath(tree, path, &c); for (j = c; j >= 1; --j) { printf("%d ", path[j]); } printf("\n\n"); int m = INT_MIN; max = maxSumPath(tree, max_path, side_path, &c, &m, &cm); for (j = 1; j <= cm ; ++j) { printf("%d ", max_path[j]); } printf("\n\n"); return 0; }
/* Driver function to test above functions */ int main() { struct node *root = NULL; /* Constructing tree given in the above figure */ root = newNode(10); root->left = newNode(-2); root->right = newNode(7); root->left->left = newNode(8); root->left->right = newNode(-4); printf ("Following are the nodes on the maximum sum path \n"); int sum = maxSumPath(root); printf ("\nSum of the nodes is %d ", sum); getchar(); return 0; }
int main() { int ar1[] = {2, 3, 7, 10, 12, 15, 30, 34}; int ar2[] = {1, 5, 7, 8, 10, 15, 16, 19}; maxSumPath(ar1, sizeof(ar1)/sizeof(ar1[0]), ar2, sizeof(ar2)/sizeof(ar2[0])); }
int maxSumPath(struct node *root, int *max_path, int *side_path, int *c, int *max, int *cm) { if(root == NULL) { *c = 0; return 0; } int l, r, cl, cr, side_max, left[M], right[M], k; l = maxSumPath(root->left, max_path, left, &cl, max, cm); r = maxSumPath(root->right, max_path, right, &cr, max, cm); if(l>r) { if(l>0) { side_max = l + root->a; for (k = 0; k <= cl; ++k) { side_path[k] = left[k]; } side_path[cl + 1] = root->a; *c = cl + 1; } else { side_max = root->a; side_path[1] = root->a; *c = 1; } } else { if(r>0) { side_max = r + root->a; for (k = 0; k <= cr; ++k) { side_path[k] = right[k]; } side_path[cr + 1] = root->a; *c = cr + 1; } else { side_max = root->a; side_path[1] = root->a; *c = 1; } } if(*max < (l + r + root->a) || *max < side_max) { if((l + r + root->a) > side_max) { *max = l + r +root->a; for (k = 1; k <= cl; ++k) max_path[k] = left[k]; max_path[cl+1] = root->a; for (k = 1; k <= cr; ++k) max_path[k + cl + 1] = right[cr - k + 1]; *cm = cl + cr + 1; } else { *max = side_max; for (k = 1; k <= *c ; ++k) { max_path[k] = side_path[k]; } *cm = *c; } } return side_max; }