leetcode 538. Convert BST to Greater Tree

来源:互联网 发布:网站手机号码提取软件 编辑:程序博客网 时间:2024/04/29 06:24

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.

Example:

Input: The root of a Binary Search Tree like this:              5            /   \           2     13Output: The root of a Greater Tree like this:             18            /   \          20     13
此题为中序遍历思想的应用,先root->right,再root,最后root->left;并把得到的和传入下一个结点。
class Solution {public:    TreeNode* convertBST(TreeNode* root) {        Inorder(root);        return root;    }    int Inorder(TreeNode* root,int sum=0)         {        if(!root)   return sum;        else        {            sum=Inorder(root->right,sum);            return  sum=Inorder(root->left,root->val+=sum);        }    }};
                                             
0 0