538. 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树中序遍历是有序的,遍历序列右边都比左边大,所以,先中序遍历得到一数组,然后从后往前做累加,本来想在遍历一遍把树的节点val改掉,但是,还不如第一遍遍历保留了所有的节点指针,然后直接加上去就好。事实证明,方案虽然正确,但是走了好几遍弯路。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* convertBST(TreeNode* root) {
        vector<int> helper;
        vector<TreeNode*> nodes;
        midSearch(root, helper, nodes);
        
        int leftsum = 0;
        int nodeAddVal = 0;
        for(int i = helper.size() - 1; i >=0; i--)
        {
            nodeAddVal = helper[i] + leftsum;
            leftsum = leftsum + helper[i];
            nodes[i]->val = nodeAddVal;
        }
        return root;
    }
    void midSearch(TreeNode* root, vector<int>& helper, vector<TreeNode*>& nodes)
    {
        if(root == nullptr)
            return;
        midSearch(root->left, helper, nodes);
        helper.push_back(root->val);
        nodes.push_back(root);
        midSearch(root->right, helper, nodes);
    }
};

运行结果一般

Runtime: 40 ms, faster than 86.71% of C++ online submissions for Convert BST to Greater Tree.

Memory Usage: 28.7 MB, less than 14.29% of C++ online submissions forConvert BST to Greater Tree.

看了下讨论区,原来可以直接后续遍历不就好了,简单明了直接!

class Solution {
public:
    int sum=0;
    TreeNode* convertBST(TreeNode* root) {
        inorder(root);
        return root;
    }
    
    void inorder(TreeNode* root)
    {
        if(root==NULL)
            return;
        inorder(root->right);
        sum+=root->val;
        root->val=sum;
        inorder(root->left);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值