538 Convert BST to Greater Tree 把二叉搜索树转换为累加树

Posted lina2014

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了538 Convert BST to Greater Tree 把二叉搜索树转换为累加树相关的知识,希望对你有一定的参考价值。

给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。
例如:
输入: 二叉搜索树:
              5
            /   \\
           2     13
输出: 转换为累加树:
             18
            /   \\
          20     13
详见:https://leetcode.com/problems/convert-bst-to-greater-tree/description/

C++:

方法一:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* convertBST(TreeNode* root) 
    {
        int sum = 0;
        helper(root, sum);
        return root;
    }
    void helper(TreeNode*& node, int& sum)
    {
        if (!node)
        {
            return;
        }
        helper(node->right, sum);
        node->val += sum;
        sum = node->val;
        helper(node->left, sum);
    }
};

 方法二:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* convertBST(TreeNode* root) {
        if (!root)
        {
            return nullptr;
        }
        int sum = 0;
        stack<TreeNode*> stk;
        TreeNode *p = root;
        while (p || !stk.empty())
        {
            while (p)
            {
                stk.push(p);
                p = p->right;
            }
            p = stk.top(); 
            stk.pop();
            p->val += sum;
            sum = p->val;
            p = p->left;
        }
        return root;
    }
};

 参考:http://www.cnblogs.com/grandyang/p/6591526.html

以上是关于538 Convert BST to Greater Tree 把二叉搜索树转换为累加树的主要内容,如果未能解决你的问题,请参考以下文章

538. Convert BST to Greater Tree

538. Convert BST to Greater Tree

538. Convert BST to Greater Tree

538. Convert BST to Greater Tree

Leetcode 538. Convert BST to Greater Tree

[LeetCode] 538. Convert BST to Greater Tree