1. Sequential Insertion
Intuition
Initialize root with preorder[0]. For each subsequent element in preorder, call standard BST insert(root, val). In the worst case (already sorted array producing a skewed tree), each insertion takes O(N), yielding O(N2) total time.
When to apply: Basic baseline when constraints are very small.
Algorithm
- Step 1: Set
root = TreeNode(preorder[0]). - Step 2: Loop i from 1 to N - 1:
insert(root, preorder[i]). - Step 3: Return
root.
#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* bstFromPreorder(vector<int>& preorder) { if (preorder.empty()) return nullptr; TreeNode* root = new TreeNode(preorder[0]); for (size_t i = 1; i < preorder.size(); i++) insert(root, preorder[i]); return root; }}; int main() { vector<int> pre = {8, 5, 1, 7, 10, 12}; Solution sol; TreeNode* root = sol.bstFromPreorder(pre); cout << "Root: " << root->val << ", Left: " << root->left->val << ", Right: " << root->right->val << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2) worst-case, O(N log N) average - Space complexity:
O(H) recursion stack