1382. Balance a Binary Search Tree

/**
 * 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:
    vector<int> sorted;
    void inorder(TreeNode* root)
    {
        if (!root) return;
        inorder(root->left);
        sorted.push_back(root->val);
        inorder(root->right);
    }

    TreeNode* construct(vector<int>& sorted, int left, int right)
    {
        if (left > right) return nullptr;
        int mid = (left + right) / 2;
        TreeNode* root = new TreeNode(sorted[mid]);
        root->left = construct(sorted, left, mid - 1);
        root->right = construct(sorted, mid + 1, right);
        return root;
    }

public:
    TreeNode* balanceBST(TreeNode* root)
    {
        inorder(root);
        return construct(sorted, 0, sorted.size() - 1);
    }
};
  • T: O(N)O(N)
  • S: O(N)O(N)