Home Leetcode 106 - Construct Binary Tree from Inorder and Postorder Traversal
Post
Cancel

Leetcode 106 - Construct Binary Tree from Inorder and Postorder Traversal

Link to problem

Problem

Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.

Solution

  • We can see that the last element of the postorder sequence is the root of the tree.
  • The location of this element in inorder sequence seperates left subtree and the right subtree.
  • For postorder sequence, we could determin the elements for left and right subtree from the inorder sequence. The relative location (left/right subtree) of element in sequence in preserved even in postorder traverse. (In post order, we visited the nodes in the order LRV)
  • Now we could see that the divided sequence is the same subproblem. Therefore, by doing the above recursively, we could rebuild the whole tree.

Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
 * 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) {}
 * };
 */
class Solution {
public:
    TreeNode* runner(vector<int>& inorder, vector<int>& postorder,
                     int in_left, int in_right, int post_left, int post_right) {
        if (in_left > in_right || post_left > post_right) return nullptr;

        TreeNode* root = new TreeNode(postorder[post_right]);
        int mid = in_left;
        while (inorder[mid] != postorder[post_right]) mid++;

        int post_offset = mid-in_left;

        root->left = runner(inorder, postorder, in_left, mid-1, post_left, post_left+post_offset-1);
        root->right = runner(inorder, postorder, mid+1, in_right, post_left+post_offset, post_right-1);

        return root;
    }

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if (inorder.empty()) return nullptr;

        int n = inorder.size();

        return runner(inorder, postorder, 0, n-1, 0, n-1);
    }
};
This post is licensed under CC BY 4.0 by the author.