← Home

105. Construct Binary Tree from Preorder and Inorder Traversal

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
105

The trick here is to name the state correctly, then let the implementation follow. For 105. Construct Binary Tree from Preorder and Inorder Traversal, the solution in this repository is mainly a two pointers solution.

Guide

What?

Before optimizing anything, pin down what information is still useful after each move. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, sliding window.

The notes already sitting in the source point us in the right direction:

  • recursion

Guide

When?

Use this approach when the hard part is not syntax, but deciding what must stay true after every update. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are buildTree, linorder, lpreorder, rpreorder, rinorder.

Guide

Why?

The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//recursion
02//Runtime: 76 ms, faster than 12.67% of C++ online submissions for Construct Binary Tree from Preorder and Inorder Traversal.
03//Memory Usage: 75.4 MB, less than 5.21% of C++ online submissions for Construct Binary Tree from Preorder and Inorder Traversal.
04/**
05 * Definition for a binary tree node.
06 * struct TreeNode {
07 *     int val;
08 *     TreeNode *left;
09 *     TreeNode *right;
10 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
11 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
12 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
13 * };
14 */
15class Solution {
16public:
17    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
18        if(preorder.empty()) return nullptr;
19        
20        TreeNode* root = new TreeNode(preorder[0]);
21        
22        int split = find(inorder.begin(), inorder.end(), preorder[0]) - inorder.begin();
23        
24        vector<int> linorder(inorder.begin(), inorder.begin()+split);
25        vector<int> lpreorder(preorder.begin()+1, preorder.begin()+1+linorder.size());
26        root->left = buildTree(lpreorder, linorder);
27        
28        vector<int> rpreorder(preorder.begin()+1+linorder.size(), preorder.end());
29        vector<int> rinorder(inorder.begin()+split+1, inorder.end());
30        root->right = buildTree(rpreorder, rinorder);
31        
32        return root;
33    }
34};
35
36//recursion
37//use index as argument to avoid copy the whole vector
38//use hashmap to record "split" values
39//https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/discuss/34538/My-Accepted-Java-Solution
40//Runtime: 24 ms, faster than 77.75% of C++ online submissions for Construct Binary Tree from Preorder and Inorder Traversal.
41//Memory Usage: 26.9 MB, less than 5.10% of C++ online submissions for Construct Binary Tree from Preorder and Inorder Traversal.
42class Solution {
43public:
44    unordered_map<int, int> inorder_indices;
45    
46    TreeNode* buildTree(vector<int>& preorder, int prestart, int preend, 
47        vector<int>& inorder, int instart, int inend){
48        //[prestart, preend], [inorder, inend] are inclusive
49        if(prestart > preend) return nullptr;
50        
51        TreeNode* root = new TreeNode(preorder[prestart]);
52        
53        // int split = find(inorder.begin()+instart, 
54        //     inorder.begin()+inend+1, root->val)-inorder.begin();
55        int split = inorder_indices[root->val];
56        int left_size = split - instart;
57        
58        root->left = buildTree(preorder, prestart+1, prestart+1+left_size-1, 
59                               inorder, instart, split-1);
60        
61        root->right = buildTree(preorder, prestart+left_size+1, preend, 
62                                inorder, split+1, inend);
63        
64        return root;
65    }
66    
67    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
68        int n = preorder.size();
69        
70        for(int i = 0; i < n; ++i){
71            inorder_indices[inorder[i]] = i;
72        }
73        
74        return buildTree(preorder, 0, n-1, inorder, 0, n-1);
75    }
76};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.