1,题目要求
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.
给定二进制搜索树(BST),将其转换为更大树,使原始BST的每个键都更改为原始键加上所有键的总和大于BST中的原始键。
2,题目思路
这道题,是树相关的题目,因此,用到了递归的策略。
在分析了这道题之后,我们可以看到,每一个节点的新值,都等于该节点的值加上其所有右侧节点的值的和。
因此,我们可以按照右-中-左的顺序来对树进行一个遍历,非常规的树的遍历方法。
在遍历过程中,记录每个节点的和,用于给下一个节点的值更新。
这样,就可以对树的值进行更新了。
同时,为了方便操作,我们定义一个辅助函数,以方便我们对树进行遍历。
3,代码实现
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
travelHelper(root);
return root;
}
void travelHelper(TreeNode* node){
if(!node)
return;
if(node->right)
travelHelper(node->right);
curSum += node->val;
node->val = curSum;
if(node->left)
travelHelper(node->left);
}
private:
int curSum = 0;
};