1. Flatten, Insert into Sorted Array, Reconstruct Tree
Intuition
Traverse tree inorder to get array vals. Insert val into vals using binary search or insertion. Then rebuild a height-balanced BST using midpoint recursion. While correct, this takes O(N) time and O(N) auxiliary space, whereas standard BST insertion requires only O(H) time.
When to apply: When guaranteed rebalancing is required and O(N) allocation is acceptable.
Algorithm
- Extract all nodes via inorder traversal into an array, insert the new value into its sorted position, and rebuild a balanced BST.
#include <iostream>#include <vector> struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}}; class Solution { void inorder(TreeNode* root, std::vector<int>& vals) { if (!root) return; inorder(root->left, vals); vals.push_back(root->val); inorder(root->right, vals); } TreeNode* build(const std::vector<int>& vals, int l, int r) { if (l > r) return nullptr; int mid = l + (r - l) / 2; TreeNode* node = new TreeNode(vals[mid]); node->left = build(vals, l, mid - 1); node->right = build(vals, mid + 1, r); return node; }public: TreeNode* insertIntoBST(TreeNode* root, int val) { std::vector<int> vals; inorder(root, vals); // Insert val in sorted order std::vector<int> combined; bool inserted = false; for (int v : vals) { if (!inserted && val < v) { combined.push_back(val); inserted = true; } combined.push_back(v); } if (!inserted) combined.push_back(val); return build(combined, 0, (int)combined.size() - 1); }}; int main() { TreeNode* root = new TreeNode(4); root->left = new TreeNode(2); root->right = new TreeNode(7); root->left->left = new TreeNode(1); root->left->right = new TreeNode(3); Solution sol; TreeNode* res = sol.insertIntoBST(root, 5); std::cout << "Root: " << res->val << " (Right: " << res->right->val << ")" << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(N)