LeetCode-Convert BST to Greater Tree

这道题只要想到方法以后并不难,就是先遍历右边子树,然后设置一个全局变量来计算和,将右边的和加上当前节点的和都加起来作为当前节点的值即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 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 {
private:
int sum=0;
public:
TreeNode* convertBST(TreeNode* root) {
if(root==nullptr) return root;
convertBST(root->right);
sum+=root->val;
root->val=sum;
convertBST(root->left);
return root;
}
};