LeetCode 538 converts binary search tree to accumulative tree

LeetCode 538 converts binary search tree to accumulative tree

Topic link

Given a binary search tree (Binary Search Tree), convert it into a cumulative tree (Greater Tree), so that the value of each node is the original node value plus the sum of all node values ​​greater than it.

E.g:

Input: Original binary search tree:

	  5
    /   \
   2     13

Output: Converted to cumulative tree:

     18
    /   \
  20     13

The weight of each point is stored in an array and then sorted, the prefix sum is calculated, and then the position of each point whose dichotomy is larger than it is updated, and the AC code is as follows:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    TreeNode* convertBST(TreeNode* root) {
    
    
        vector<int>v,sum;
        queue<TreeNode*>q;
        q.push(root);
        while(!q.empty()){
    
    
            TreeNode* t=q.front();
            q.pop();
            if(t){
    
    
                v.push_back(t->val);
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
        }
        sort(v.begin(),v.end());
        sum.push_back(0);
        for(auto i:v) sum.push_back(sum.back()+i);
        q.push(root);
        while(!q.empty()){
    
    
            TreeNode* t=q.front();
            q.pop();
            if(t){
    
    
                int pos=upper_bound(v.begin(),v.end(),t->val)-v.begin();
                t->val=sum.back()-sum[pos-1];
                if(t->left) q.push(t->left);
                if(t->right) q.push(t->right);
            }
        }
        return root;
    }
};

Guess you like

Origin blog.csdn.net/qq_43765333/article/details/108716411