码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-04-23 00:13:09      阅读:525      评论:0      收藏:0      [点我收藏+]

标签:bin   leetcode   sea   com   大于   原来   arc   stack   参考   

给定一个二叉搜索树(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 把二叉搜索树转换为累加树

标签:bin   leetcode   sea   com   大于   原来   arc   stack   参考   

原文地址:https://www.cnblogs.com/xidian2014/p/8910068.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!