解题思路:从右往左遍历(右->根->左),需要一个全局变量缓存整个右半部分的值
代码
/**
* 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:
int sums = 0;
void selution(TreeNode* root) {
if (root == NULL) return;
selution(root -> right);
sums += root -> val;
root -> val = sums;
selution(root->left);
}
TreeNode* bstToGst(TreeNode* root) {
selution(root);
return root;
}
};
网友评论