Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit adf424d

Browse files
Binary tree max path sum
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 6eabacf commit adf424d

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all:
2+
gcc -O2 -o test bst_max_path.c
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
#include <limits.h>
4+
5+
struct TreeNode {
6+
int val;
7+
struct TreeNode *left;
8+
struct TreeNode *right;
9+
};
10+
11+
static int recursive(struct TreeNode *node, int *max)
12+
{
13+
int left_max = 0;
14+
int right_max = 0;
15+
16+
if (node->left != NULL) {
17+
left_max = recursive(node->left, max);
18+
}
19+
20+
if (node->right != NULL) {
21+
right_max = recursive(node->right, max);
22+
}
23+
24+
int sum = node->val + left_max + right_max;
25+
if (sum > *max) {
26+
*max = sum;
27+
}
28+
29+
int path_sum = node->val + (right_max > left_max ? right_max : left_max);
30+
return path_sum > 0 ? path_sum : 0;
31+
}
32+
33+
static int maxPathSum(struct TreeNode* root)
34+
{
35+
if (root == NULL) {
36+
return 0;
37+
}
38+
39+
int max = INT_MIN;
40+
recursive(root, &max);
41+
return max;
42+
}
43+
44+
int main(void)
45+
{
46+
struct TreeNode n_1, n_2, n_3, n_4, n_5, n_6, n_7;
47+
struct TreeNode n0, n1, n2, n3, n4, n5, n6, n7;
48+
49+
n_7.val = -7;
50+
n_6.val = -6;
51+
n_5.val = -5;
52+
n_4.val = -4;
53+
n_3.val = -3;
54+
n_2.val = -2;
55+
n_1.val = -1;
56+
n0.val = 0;
57+
n1.val = 1;
58+
n2.val = 2;
59+
n3.val = 3;
60+
n4.val = 4;
61+
n5.val = 5;
62+
n6.val = 6;
63+
n7.val = 7;
64+
65+
n_7.left = NULL;
66+
n_7.right = NULL;
67+
n_6.left = &n_7;
68+
n_6.right = &n_5;
69+
n_5.left = NULL;
70+
n_5.right = NULL;
71+
n_4.left = &n_6;
72+
n_4.right = &n_2;
73+
n_3.left = NULL;
74+
n_3.right = NULL;
75+
n_2.left = &n_3;
76+
n_2.right = &n_1;
77+
n_1.left = NULL;
78+
n_1.right = NULL;
79+
n0.left = &n_4;
80+
n0.right = &n4;
81+
n1.left = NULL;
82+
n1.right = NULL;
83+
n2.left = &n1;
84+
n2.right = &n3;
85+
n3.left = NULL;
86+
n3.right = NULL;
87+
n4.left = &n2;
88+
n4.right = &n6;
89+
n5.left = NULL;
90+
n5.right = NULL;
91+
n6.left = &n5;
92+
n6.right = &n7;
93+
n7.left = NULL;
94+
n7.right = NULL;
95+
96+
printf("%d\n", maxPathSum(&n0));
97+
return 0;
98+
}

0 commit comments

Comments
 (0)