← Home

106. Construct Binary Tree from Inorder and Postorder Traversal

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

A good way into this one is to ask: what do we need to remember so we never redo work blindly? For 106. Construct Binary Tree from Inorder and Postorder Traversal, the solution in this repository is mainly a two pointers solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. 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.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are buildTree.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • 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//Runtime: 56 ms, faster than 23.77% of C++ online submissions for Construct Binary Tree from Inorder and Postorder Traversal.
02//Memory Usage: 24.2 MB, less than 29.37% of C++ online submissions for Construct Binary Tree from Inorder and Postorder Traversal.
03/**
04 * Definition for a binary tree node.
05 * struct TreeNode {
06 *     int val;
07 *     TreeNode *left;
08 *     TreeNode *right;
09 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
10 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
11 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
12 * };
13 */
14class Solution {
15public:
16    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder, int is = -1, int ie = -1, int ps = -1, int pe = -1) {
17        if(is > ie || ps > pe) return nullptr;
18        
19        int n = inorder.size();
20        
21        if(n == 0) return nullptr;
22        
23        if(is == -1){
24            is = ps= 0;
25            ie = pe = n-1;
26        }
27        
28        TreeNode* node = new TreeNode(postorder[pe]);
29        
30        int iroot = find(inorder.begin(), inorder.end(), postorder[pe]) - inorder.begin();
31        // cout << "inorder's root at: " << iroot << endl;
32        int leftSize = iroot-is;
33        
34        node->left = buildTree(inorder, postorder, is, iroot-1, ps, ps+leftSize-1);
35        node->right = buildTree(inorder, postorder, iroot+1, ie, ps+leftSize, pe-1);
36        
37        return node;
38    }
39};
40
41//Use HashMap so we don't need to "find"
42//https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/discuss/34782/My-recursive-Java-code-with-O(n)-time-and-O(n)-space
43//Runtime: 24 ms, faster than 74.28% of C++ online submissions for Construct Binary Tree from Inorder and Postorder Traversal.
44//Memory Usage: 24 MB, less than 36.01% of C++ online submissions for Construct Binary Tree from Inorder and Postorder Traversal.
45/**
46 * Definition for a binary tree node.
47 * struct TreeNode {
48 *     int val;
49 *     TreeNode *left;
50 *     TreeNode *right;
51 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
52 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
53 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
54 * };
55 */
56class Solution {
57public:
58    unordered_map<int, int> val2idx;
59    
60    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder, int is, int ie, int ps, int pe) {
61        if(is > ie || ps > pe) return nullptr;
62        
63        TreeNode* node = new TreeNode(postorder[pe]);
64        
65        int iroot = val2idx[postorder[pe]];
66        // cout << "inorder's root at: " << iroot << endl;
67        int leftSize = iroot-is;
68        
69        node->left = buildTree(inorder, postorder, is, iroot-1, ps, ps+leftSize-1);
70        node->right = buildTree(inorder, postorder, iroot+1, ie, ps+leftSize, pe-1);
71        
72        return node;
73    };
74    
75    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
76        int n = inorder.size();
77        
78        if(n == 0) return nullptr;
79        
80        for(int i = 0; i < n; ++i){
81            val2idx[inorder[i]] = i;
82        }
83        
84        return buildTree(inorder, postorder, 0, n-1, 0, n-1);
85    }
86};

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.