0%

1038. Binary Search Tree to Greater Sum Tree

右中左序遍历,维护一个全局的sum

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* bstToGst(TreeNode* root) {
if (!root) return root;
bstToGst(root->right);
root->val = sum += root->val;
bstToGst(root->left);
return root;
}

int sum = 0;
};