LeetCode-1038:从二叉搜索树到最大和树

一、题目描述

二、解题思路

  • 二叉搜索树的中序遍历是递增序列
    • 我们可以首先中序遍历二叉搜索树,将数字存入vector
    • 新树的值为从vector末尾开始,为从末尾元素到当前的元素sum
  • 二叉搜索树的反中序遍历是递减序列
    • 反中序遍历二叉搜索树,当前元素等于当前的sum

三、解题代码

  • 中序遍历解法
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;
    }
};
  • 反中序遍历解法
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;
    }
};

四、运行结果

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务