1. Recursive Construction with Linear Search
Intuition
At each step, linearly find rootVal in the inorder array. This takes O(n) per level, resulting in O(n2) time for skewed trees.
When to apply: Basic baseline check.
Algorithm
- Step 1: If inStart > inEnd return null.
- Step 2: rootVal = postorder[postEnd].
- Step 3: Linearly scan inorder[inStart ... inEnd] to find inRoot where inorder[inRoot] == rootVal.
- Step 4: numLeft = inRoot - inStart.
- Step 5: Recurse for left and right subtrees.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: TreeNode* build(vector<int>& in, int inS, int inE, vector<int>& post, int postS, int postE) { if (inS > inE || postS > postE) return nullptr; int rootVal = post[postE]; TreeNode* root = new TreeNode(rootVal); int inRoot = inS; while (in[inRoot] != rootVal) inRoot++; int numLeft = inRoot - inS; root->left = build(in, inS, inRoot - 1, post, postS, postS + numLeft - 1); root->right = build(in, inRoot + 1, inE, post, postS + numLeft, postE - 1); return root; } TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { return build(inorder, 0, inorder.size() - 1, postorder, 0, postorder.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) at each node. - Space complexity:
O(h)— Recursion stack depth O(h).