zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    PowerGhost
    watchdogs感染性挖矿病毒
    XorDDoS木马
    Gates(盖茨)木马
    seasame病毒
    zabbix监控之邮件报警通知
    ubuntu18.04 heirloom-mailx 通过外部SMTP服务器发送邮件
    linux小常识
    zabbix基本概念
    Zabbix图表中文乱码
  • 原文地址:https://www.cnblogs.com/immjc/p/7147857.html
Copyright © 2011-2022 走看看