LeetCode 538 The road of LeetCode to transform a binary tree into a cumulative number HERODING

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

Problem-solving idea: I
felt very puzzled at the beginning to write this question. Why is this complicated question a simple question? Later, after careful observation of the question, I finally found out that this is a binary search tree, so it means for each node , The value of the right child node must be greater than the value of the current node, the value of the left child node must be smaller than the current value, then the left child node must add the value of the root node and the value of the right child node, and the current root must add the right child The value of the node and the value of the right child node remain unchanged, so the overall idea is to traverse the sequence, the 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:
    int sum = 0;

    TreeNode* convertBST(TreeNode* root) {
    
    
        if (root != nullptr) {
    
    
            convertBST(root->right);
            sum += root->val;
            root->val = sum;
            convertBST(root->left);
        }
        return root;
    }
};

Guess you like

Origin blog.csdn.net/HERODING23/article/details/108701942
Recommended