您的位置:首页 > 编程语言 > C语言/C++

lintcode_Convert BST to Greater Tree

2017-05-21 23:17 281 查看
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.

您在真实的面试中是否遇到过这个题? 

Yes

样例

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.感想:

这个题一开始想复杂了,总想着先去遍历一遍记录所有节点值,结果越走越远
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息