1. Sequential BST Insertion
Intuition
Inserting elements from an already-sorted array sequentially into a standard BST creates a completely degenerate right-skewed tree (linked list) of height N, resulting in O(N2) insertion time and O(N) search depth.
When to apply: Naive baseline demonstrating why unbalanced insertion fails.
Algorithm
- Step 1: Create root with nums[0].
- Step 2: Loop i from 1 to N - 1, call standard BST insert.
- Step 3: Result is unbalanced with height N.
#include <iostream>#include <vector>using namespace std; struct TreeNode { int val; TreeNode *left, *right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}}; class Solution { TreeNode* insert(TreeNode* root, int val) { if (!root) return new TreeNode(val); if (val < root->val) root->left = insert(root->left, val); else root->right = insert(root->right, val); return root; }public: TreeNode* sortedArrayToBST(vector<int>& nums) { if (nums.empty()) return nullptr; TreeNode* root = new TreeNode(nums[0]); for (size_t i = 1; i < nums.size(); i++) insert(root, nums[i]); return root; }}; int main() { vector<int> nums = {-10, -3, 0, 5, 9}; Solution sol; TreeNode* root = sol.sortedArrayToBST(nums); cout << "Root: " << root->val << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2) - Space complexity:
O(N) skewed tree depth