-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.c
35 lines (34 loc) · 853 Bytes
/
Solution.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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* bstToGst(struct TreeNode* root) {
struct TreeNode* cur = root;
int sum = 0;
while (cur) {
if (!cur->right) {
sum += cur->val;
cur->val = sum;
cur = cur->left;
} else {
struct TreeNode* next = cur->right;
while (next->left && next->left != cur) {
next = next->left;
}
if (!next->left) {
next->left = cur;
cur = cur->right;
} else {
next->left = NULL;
sum += cur->val;
cur->val = sum;
cur = cur->left;
}
}
}
return root;
}