Leetcode:1038

给出二叉 搜索 树的根节点,该二叉树的节点值各不相同,修改二叉树,使每个节点 node 的新值等于原树中大于或等于 node.val 的值之和。

提醒一下,二叉搜索树满足下列约束条件:

节点的左子树仅包含键 小于 节点键的节点。 节点的右子树仅包含键 大于 节点键的节点。 左右子树也必须是二叉搜索树。   思路: 右中左遍历树, 使用一个数存储当前和

void calculate(TreeNode* root, int & pre_value){
    if(root== nullptr)
        return;
    calculate(root->right, pre_value);
    root->val += pre_value;
    pre_value = root->val;
    calculate(root->left, pre_value);

}

TreeNode* bstToGst(TreeNode* root) {
    if(root== nullptr)
        return nullptr;
    int pre_val =0;
    calculate(root, pre_val);
    return root;
}