lintcode_Convert BST to Greater Tree

来源:互联网 发布:铆工放样软件 编辑:程序博客网 时间:2024/04/25 02:36

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.

样例

Given a binary search Tree `{5,2,3}`:

              5            /   \           2     13

Return the root of new tree

             18            /   \          20     13
2.思路:

先找到最右节点,从右往左依次更新节点值即可

3.代码:

int rr=0;
    TreeNode* convertBST(TreeNode* root) {
        if(root==NULL) return NULL; 
        else {
        convertBST(root->right);
        root->val+=rr;
        rr=root->val;
        convertBST(root->left);
        }
        return root;
    }

4.感想:

这个题一开始想复杂了,总想着先去遍历一遍记录所有节点值,结果越走越远