leetcode 538. Convert BST to Greater Tree

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     13

Output: 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);
        }
    }
};

版权声明:本文为hhy_111原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。