Skip to content

Latest commit

 

History

History
34 lines (31 loc) · 761 Bytes

538.md

File metadata and controls

34 lines (31 loc) · 761 Bytes

538. 把二叉搜索树转换为累加树

反序中序遍历

时间复杂度:O(n)。

/**
 * 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 {
private:
    int pre = 0;
public:
    TreeNode* convertBST(TreeNode* root) {
        if (!root) {
            return nullptr;
        }
        convertBST(root->right);
        root->val += pre;
        pre = root->val;
        convertBST(root->left);
        return root;
    }
};