-
Notifications
You must be signed in to change notification settings - Fork 0
/
1038 Binary Search Tree to Greater Sum Tree.c
96 lines (75 loc) · 2.33 KB
/
1038 Binary Search Tree to Greater Sum Tree.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int count_nodes(struct TreeNode * root)
{
if(root == NULL)
return 0;
return (1 + count_nodes(root->left) + count_nodes(root->right));
}
void inorder(struct TreeNode * root, struct TreeNode ** inorder_arr, int * inorder_arr_index)
{
if(root == NULL)
return;
inorder(root->left, inorder_arr, inorder_arr_index);
inorder_arr[(*inorder_arr_index)++] = root;
inorder(root->right, inorder_arr, inorder_arr_index);
}
struct TreeNode * create_gst(struct TreeNode ** gst_root, struct TreeNode * root, bool * first)
{
if(root == NULL)
return NULL;
struct TreeNode * new_node = (struct TreeNode *)malloc(sizeof(struct TreeNode));
new_node->val = root->val;
new_node->left = NULL;
new_node->right = NULL;
if(*first == true)
{
*gst_root = new_node;
*first = false;
}
new_node->left = create_gst(gst_root, root->left, first);
new_node->right = create_gst(gst_root, root->right, first);
return new_node;
}
struct TreeNode* bstToGst(struct TreeNode* root)
{
int nodes = count_nodes(root);
struct TreeNode ** inorder_arr = (struct TreeNode **)malloc(sizeof(struct TreeNode *) * nodes);
int inorder_arr_index = 0;
inorder(root, inorder_arr, &inorder_arr_index);
int * inorder_arr_val = (int *)malloc(sizeof(int) * nodes);
int inorder_arr_val_index = 0;
int i=0;
int sum = 0;
for(i=0; i<nodes; i++)
{
inorder_arr_val[i] = inorder_arr[i]->val;
sum += inorder_arr[i]->val;
}
int current_sum = 0;
for(i=0; i<nodes; i++)
{
current_sum += inorder_arr_val[i];
inorder_arr_val[i] += (sum - current_sum);
}
struct TreeNode * gst_root = NULL;
bool first = true;
create_gst(&gst_root, root, &first);
struct TreeNode ** gst_arr = (struct TreeNode **)malloc(sizeof(struct TreeNode *) * nodes);
int gst_arr_index = 0;
inorder(gst_root, gst_arr, &gst_arr_index);
for(i=0; i<nodes; i++)
{
gst_arr[i]->val = inorder_arr_val[i];
}
free(inorder_arr);
free(inorder_arr_val);
free(gst_arr);
return gst_root;
}