LeetCode-1038: from a binary search tree to tree and maximum

One, Title Description

Here Insert Picture Description

Second, problem-solving ideas

  • Preorder binary search tree is increasing sequence
    • First, we can preorder binary search tree, digital depositvector
    • The new tree is from vectorthe end of the beginning, from the end of the current element to elementsum
  • Trans inorder traversal of the binary search tree is a descending sequence
    • Anti inorder traversal binary search tree, the current equal to the current elementsum

Third, the problem-solving Code

  • Preorder solution
class Solution {
public:
    TreeNode* bstToGst(TreeNode* root) {
        if(!root)   return root;
        vector<int> vec;
        stack<TreeNode*>s;
        auto p = root;
        while(!s.empty() || p){
            while(p){
                s.push(p);
                p = p->left;
            }
            if(!s.empty()){
                p = s.top();
                s.pop();
                vec.push_back(p->val);
                p = p->right;
            }
        }
        int sum = 0;
        for(auto i = vec.rbegin(); i != vec.rend(); i++){
            sum += *i;
            *i = sum;
        }
        int counter = 0;
        p = root;
        while(!s.empty() || p){
            while(p){
                s.push(p);
                p = p->left;
            }
            if(!s.empty()){
                p = s.top();
                s.pop();
                //vec.push_back(p->val);
                p->val = vec[counter++];
                p = p->right;
            }
        }
        return root;
    }
};
  • Anti preorder Solution
class Solution {
public:
    int sum = 0;
public:
    TreeNode* bstToGst(TreeNode* root) {
        if(root){
            root->right = bstToGst(root->right);
            sum += root->val;
            root->val = sum;
            root->left = bstToGst(root->left);
        }
        return root;
    }
};

Fourth, operating results

Here Insert Picture Description

Published 30 original articles · won praise 3 · Views 814

Guess you like

Origin blog.csdn.net/weixin_44587168/article/details/105338640