[LeetCode] Convert BST to Greater Tree

Posted immjc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 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
题目要求将一个BST转换成一个每个节点数值更大的数,要求在全树范围内将比本节点大的所有节点值相加到本节点。由二叉树的中序遍历可知,节点值为:(左) (中) (右)。转换后的树的节点值为:(左 + 中 + 右) (中 + 右) (右)。可以用一个sum值表示每次节点需要相加的值,利用递归传递这个sum。最后完成BST转换。核心是使用逆中序遍历进行遍历生成新的树。
class Solution {
public:
    TreeNode* convertBST(TreeNode* root) {
        int sum = 0;
        convertBSTcore(root, sum);
        return root;
    }
    void convertBSTcore(TreeNode* root, int& sum) {
        if (root == nullptr)
            return;
        convertBSTcore(root->right, sum);
        root->val += sum;
        sum = root->val;
        convertBSTcore(root->left, sum);
    }
};
// 36 ms

用迭代完成该过程。

class Solution {
public:
    TreeNode* convertBST(TreeNode* root) {
        if (root == nullptr)
            return 0;
        int sum = 0;
        stack<TreeNode*> s;
        TreeNode* node = root;
        while (node != nullptr || !s.empty()) {
            while (node != nullptr) {
                s.push(node);
                node = node->right;
            }
            node = s.top();
            s.pop();
            node->val += sum;
            sum = node->val;
            node = node->left;
        }
        return root;
    }
};
// 35 ms

 

以上是关于[LeetCode] Convert BST to Greater Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode - Convert BST to Greater Tree

LeetCode:Convert BST to Greater Tree

Leetcode 538. Convert BST to Greater Tree

[LeetCode] 538. Convert BST to Greater Tree

LeetCode: Convert BST to Greater Tree

LeetCode算法题-Convert BST to Greater Tree(Java实现)