Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitb45b88a

Browse files
authored
Created Convert_BST_to_Greater_tree.md
1 parentd69362e commitb45b88a

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#Convert BST to Greater Tree
2+
###Problem link:[Click me](https://leetcode.com/problems/convert-bst-to-greater-tree/)
3+
---
4+
5+
-##Question:
6+
>Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus
7+
the sum of all keys greater than the original key in BST.
8+
>>Example :
9+
10+
4
11+
12+
/ \
13+
14+
1 6
15+
16+
/ \ / \
17+
18+
0 2 5 7
19+
20+
\ \
21+
22+
3 8
23+
24+
25+
Input: root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
26+
Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
27+
28+
---
29+
30+
-##Solution:
31+
**Code :**
32+
33+
```cpp
34+
/**
35+
* Definition for a binary tree node.
36+
* struct TreeNode {
37+
* int val;
38+
* TreeNode *left;
39+
* TreeNode *right;
40+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
41+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
42+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
43+
* };
44+
*/
45+
classSolution {
46+
public:
47+
TreeNode* convertBST(TreeNode* root) {
48+
int cur_sum = 0;
49+
convertBSTHelper(root, &cur_sum);
50+
return root;
51+
}
52+
53+
private:
54+
void convertBSTHelper(TreeNode* root, int*cur_sum) {
55+
if (!root) {
56+
return;
57+
}
58+
59+
if (root->right) {
60+
convertBSTHelper(root->right, cur_sum);
61+
}
62+
root->val = (*cur_sum += root->val);
63+
if (root->left) {
64+
convertBSTHelper(root->left, cur_sum);
65+
}
66+
}
67+
};
68+
```
69+
70+
**Time Complexity : O(n)**
71+
72+
---
73+
74+
Reference :[Dev to](https://dev.to/)
75+
76+

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp