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.

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

C实现:

/**
 * Definition for a binary tree node.
 * struct TreeNode 
 * {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

cur_sum = 0;

struct TreeNode* convertBST(struct TreeNode* root) 
{
    struct TreeNode **stack = NULL;   
    int cur = 0;
    struct TreeNode * p = root;
    struct TreeNode * res = NULL;
    int tmp = 0 ,sum = 0;
    
    while(p || cur > 0)
    {
        while(p)
        {
            /*入栈*/
            stack = (struct TreeNode **)realloc(stack,sizeof(struct TreeNode *) * (cur + 1));
            stack[cur++] = p;
            p = p->right;
        }
        
        res = stack[--cur];
        
        tmp = sum;
        sum += res->val;
        res->val = res->val + tmp;
        
        p = res->left;
        
        
    }
    
    return root;
}