--- tags: leetcode --- # [105. Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/) --- # My Solution ## The Key Idea for Solving This Coding Question ## C++ Code ```cpp= /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ struct Solution { public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { for (int i = 0; i < inorder.size(); ++i) { inorderValToIdx[inorder[i]] = i; } return buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1); } private: unordered_map<int, int> inorderValToIdx; TreeNode *buildTree(vector<int> &preorder, int preHead, int preTail, vector<int> &inorder, int inHead, int inTail) { if (preHead > preTail || inHead > inTail) { return nullptr; } TreeNode *node = new TreeNode(preorder[preHead]); int inRootIdx = inorderValToIdx[preorder[preHead]]; int leftSize = inRootIdx - inHead; node->left = buildTree(preorder, preHead + 1, preHead + leftSize, inorder, inHead, inRootIdx - 1); node->right = buildTree(preorder, preHead + leftSize + 1, preTail, inorder, inRootIdx + 1, inTail); return node; } }; ``` ## Time Complexity $O(n)$ * $n$ is the number of the nodes in the binary tree. ## Space Complexity $O(H + n)$ or $O(n)$ * We use a hash map to store the mapping between inorder values and their index. For this part, the space complexity is $O(n)$. * We also create a new TreeNode object for each node. For this part, the space complexity is $O(n)$. * The recursion calls also use space for stack and the space complexity is $O(H)$, where $H$ is the height of the binary tree. * Therefore, the space complexity is $O(H + n)$. * For the best case, the height of the tree is $logn$, which is a balanced binary tree, so the best space complexity is $O(logn + n)$. * For the worst case, the height of the tre is $n$, which is a skew binary tree. The worst space complexity is $O(n)$. * If the number of nodes is considerably large (ie n approximately infinity), we can say the space complexity is $O(n)$. # Miscellaneous [889. Construct Binary Tree from Preorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-postorder-traversal/) <!-- # Test Cases ``` [3,9,20,15,7] [9,3,15,20,7] ``` ``` [-1] [-1] ``` ``` [1,2,3] [1,3,2] ``` -->