1. Collect Values, Sort, and Rebuild
Intuition
Traverse the tree using any traversal (e.g. preorder or BFS) to extract all values into a list. Sort the list in O(N log N) time. Then recursively build the balanced BST by choosing the midpoint of the sorted range as the root.
When to apply: Naive baseline when unaware that BST inorder traversal is already sorted.
Algorithm
- Step 1: Traverse the tree using preorder or BFS to collect all values into an array.
- Step 2: Sort the array in O(N log N) time.
- Step 3: Define
build(L, R): pickmid = (L + R) / 2as root, recurse on[L, mid - 1]for left child, and[mid + 1, R]for right child.
#include <iostream>#include <vector>#include <algorithm>using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}}; class Solution { void collect(TreeNode* root, vector<int>& vals) { if (!root) return; vals.push_back(root->val); collect(root->left, vals); collect(root->right, vals); } TreeNode* build(const vector<int>& vals, int l, int r) { if (l > r) return nullptr; int mid = l + (r - l) / 2; TreeNode* root = new TreeNode(vals[mid]); root->left = build(vals, l, mid - 1); root->right = build(vals, mid + 1, r); return root; }public: TreeNode* balanceBST(TreeNode* root) { vector<int> vals; collect(root, vals); sort(vals.begin(), vals.end()); return build(vals, 0, (int)vals.size() - 1); }}; int main() { TreeNode* root = new TreeNode(1); root->right = new TreeNode(2); root->right->right = new TreeNode(3); root->right->right->right = new TreeNode(4); Solution sol; TreeNode* balanced = sol.balanceBST(root); cout << "Balanced Root: " << balanced->val << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N) - Space complexity:
O(N)