1. Linear Inorder Search Recursion
Intuition
Linear scan to find root index in inorder array. Runs in O(n2) worst case on skewed trees.
When to apply: Basic baseline check.
Algorithm
- Step 1: If preStart > preEnd return null.
- Step 2: rootVal = preorder[preStart].
- Step 3: Linearly find inRoot where inorder[inRoot] == rootVal.
- Step 4: numLeft = inRoot - inStart.
- Step 5: Recurse left and right.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: TreeNode* build(vector<int>& pre, int preS, int preE, vector<int>& in, int inS, int inE) { if (preS > preE || inS > inE) return nullptr; int rootVal = pre[preS]; TreeNode* root = new TreeNode(rootVal); int inRoot = inS; while (in[inRoot] != rootVal) inRoot++; int numLeft = inRoot - inS; root->left = build(pre, preS + 1, preS + numLeft, in, inS, inRoot - 1); root->right = build(pre, preS + numLeft + 1, preE, in, inRoot + 1, inE); return root; } TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { return build(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n^2)— Linear search inside subarray takes O(n) per level. - Space complexity:
O(h)— Recursion call stack takes O(h).