# 538. Convert BST to Greater Tree，思考方式很重要

Given 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 sum of all keys greater than the original key in BST.

Example:

Input: The root of a Binary Search Tree like this:
5
/   \
2     13

Output: The root of a Greater Tree like this:
18
/   \
20     13

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode() : val(0), left(nullptr), right(nullptr) {}
*     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
*     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
vector<int> helper;
vector<TreeNode*> nodes;
midSearch(root, helper, nodes);

int leftsum = 0;
for(int i = helper.size() - 1; i >=0; i--)
{
leftsum = leftsum + helper[i];
}
return root;
}
void midSearch(TreeNode* root, vector<int>& helper, vector<TreeNode*>& nodes)
{
if(root == nullptr)
return;
midSearch(root->left, helper, nodes);
helper.push_back(root->val);
nodes.push_back(root);
midSearch(root->right, helper, nodes);
}
};

Runtime: 40 ms, faster than 86.71% of C++ online submissions for Convert BST to Greater Tree.

Memory Usage: 28.7 MB, less than 14.29% of C++ online submissions forConvert BST to Greater Tree.

class Solution {
public:
int sum=0;
TreeNode* convertBST(TreeNode* root) {
inorder(root);
return root;
}

void inorder(TreeNode* root)
{
if(root==NULL)
return;
inorder(root->right);
sum+=root->val;
root->val=sum;
inorder(root->left);
}
};

01-22 1015

03-26 742

03-19 942

03-19 2641

05-14 710

06-21 204

04-14 307

03-29 390

03-21 3396

03-20 700

12-07 591

10-16 39

02-13 179

05-25 189

05-26 28

05-29 9

03-19 83万+

04-14 62万+

03-13 16万+

03-01 14万+

#### 技术大佬：我去，你写的 switch 语句也太老土了吧

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客