题目链接:https://leetcode-cn.com/problems/convert-bst-to-greater-tree/
题目如下:
/**
* 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) {
dfs(root);
return root;
}
void dfs(TreeNode* root){
if(!root) return;
dfs(root->right);
max_sum+=root->val;
root->val=max_sum;
dfs(root->left);
}
private:
int max_sum=0;
};