• [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
  • 相关阅读:
    淘宝长仁:JVM性能指标的理论极限和衡量方法(TaobaoJVM)
    你不知道的5个JVM命令行标志
    Java 内存模型 JMM
    Java虚拟机深入研究
    java内存区域——daicy
    Java里的堆(heap)栈(stack)和方法区(method)
    JVM学习笔记-操作数栈(Operand Stack)
    c# 网页打印全流程
    备忘录模式实例1
    加密程序-注册方法实现
  • 原文地址:https://www.cnblogs.com/immjc/p/7147857.html
Copyright © 2020-2023  润新知