-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbtreemaxpathsum.c
115 lines (90 loc) · 2.45 KB
/
btreemaxpathsum.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/* Copyright © 2021-2023 Chee Bin HOH. All rights reserved.
*
* Find the maximum path sum. The path may start and end at any node in the
* tree.
*/
#include "btree.h"
#include <stdio.h>
#include <stdlib.h>
int btreePathSumInternal(struct TreeNode *root, int sum) {
int lsum;
int rsum;
if (NULL == root)
return sum;
sum = sum + root->val;
lsum = sum;
rsum = sum;
if (NULL != root->left)
lsum = btreePathSumInternal(root->left, sum);
if (NULL != root->right)
rsum = btreePathSumInternal(root->right, sum);
if (lsum > sum)
sum = lsum;
if (rsum > sum)
sum = rsum;
return sum;
}
/* This is API facing method to check if there is a path of sum of value of
* nodes that matches the target value.
*/
int btreeMaximumPathSum(struct TreeNode *root) {
int sum = 0;
return btreePathSumInternal(root, sum);
}
int main(int argc, char *argv[]) {
struct TreeNode *root = NULL;
struct TreeNode *other = NULL;
root = malloc(sizeof(struct TreeNode));
root->val = 0;
root->left = NULL;
root->right = NULL;
other = malloc(sizeof(struct TreeNode));
other->val = 1;
other->left = NULL;
other->right = NULL;
root->left = other;
other = malloc(sizeof(struct TreeNode));
other->val = 3;
other->left = NULL;
other->right = NULL;
root->left->left = other;
other = malloc(sizeof(struct TreeNode));
other->val = 4;
other->left = NULL;
other->right = NULL;
root->left->right = other;
other = malloc(sizeof(struct TreeNode));
other->val = 2;
other->left = NULL;
other->right = NULL;
root->right = other;
other = malloc(sizeof(struct TreeNode));
other->val = 5;
other->left = NULL;
other->right = NULL;
root->right->right = other;
other = malloc(sizeof(struct TreeNode));
other->val = 6;
other->left = NULL;
other->right = NULL;
root->right->right->left = other;
other = malloc(sizeof(struct TreeNode));
other->val = 7;
other->left = NULL;
other->right = NULL;
root->right->right->left->right = other;
other = malloc(sizeof(struct TreeNode));
other->val = 8;
other->left = NULL;
other->right = NULL;
root->right->right->right = other;
printf("The tree topology:\n");
printTreeNodeInTreeTopology(root);
printf("\n");
printf("The maximum path sum is %d\n", btreeMaximumPathSum(root));
printf("\n");
printf("\n");
// I do not care about freeing malloced memory, OS will take care of freeing
// heap that is part of process for this one off program.
return 0;
}