-
Notifications
You must be signed in to change notification settings - Fork 0
/
1038. Binary Search Tree to Greater Sum Tree
69 lines (69 loc) · 1.53 KB
/
1038. Binary Search Tree to Greater Sum Tree
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
void Visit(TreeNode * &root_original,int & val , int & sum)
{
if(root_original==nullptr)
{
return;
}else
{
if(root_original->val>=val)
{
cout << sum << endl;
sum += root_original->val;
}
Visit(root_original->left,val,sum);
Visit(root_original->right,val,sum);
}
}
void Insert(TreeNode *& root,int sum)
{
if(root==NULL)
{
root = new TreeNode(sum);
}else if(sum<root->val)
{
Insert(root->left,sum);
}else if(sum>root->val)
{
Insert(root->right,sum);
}
}
int sum = 0;
void Call(TreeNode *& root,TreeNode *& root_2)
{
if(root_2==nullptr)
{
return;
}else
{
Visit(root,root_2->val,sum);
cout << sum << endl;
root_2->val = sum;
sum = 0;
}
Call(root,root_2->left);
Call(root,root_2->right);
}
TreeNode *root_new = nullptr;
void Deepcopy(TreeNode * &root)
{
if(root==NULL)
{
return;
}else
{
Insert(root_new,root->val);
}
Deepcopy(root->left);
Deepcopy(root->right);
}
TreeNode* bstToGst(TreeNode* root) {
if(root==nullptr)
{
return nullptr;
}else
{
Deepcopy(root);
Call(root_new,root);
}
return root;
}