../ Competitive Programming
-rw-r--r--aguang1.2 KiB1 min read

Leet Code Daily 2024-06-26 - Balance a Binary Search Tree

Code

c++
/**
 * 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 {
public:
    void collect(TreeNode* root, vector<TreeNode*>& out) {
        if (root == nullptr) {
            return;
        }
        collect(root->left, out);
        out.push_back(root);
        collect(root->right, out);
    }

    TreeNode* rebuild(vector<TreeNode*>& nodes, int l, int r) {
        if (l > r) {
            return nullptr;
        }
        int mid = (l + r) >> 1;
        nodes[mid]->left = rebuild(nodes, l, mid - 1);
        nodes[mid]->right = rebuild(nodes, mid + 1, r);
        return nodes[mid];
    }

    TreeNode* balanceBST(TreeNode* root) {
        vector<TreeNode*> nodes;
        collect(root, nodes);
        return rebuild(nodes, 0, nodes.size() - 1);
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window