105. Construct Binary Tree from Preorder and Inorder Traversal

Problem Description

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

Intuition

The front element of preorder traversal is the tree’s root node(the middle of inorder traversal). We use it to determine which elements belong the left subtree and the right subtree, and keep comparing the preorder and inorder traversals. This way, we can construct the entire tree from these two traversals.

Algorithm

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
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
for(int i = 0; i < preorder.size(); i++){
}
return build(preorder, inorder, 0, preorder.size(), 0, inorder.size());
}

TreeNode* build(vector<int>& preorder, vector<int>& inorder, int pre_start, int pre_end, int in_start, int in_end){

if(pre_start >= pre_end){
return NULL;
}
TreeNode* root = new TreeNode(preorder[pre_start]);

int split_point = -1;
for(int i = in_start; i < in_end; i++){
if(inorder[i] == preorder[pre_start]){
split_point = i;
break;
}
}

int left_size = split_point - in_start;

root->left = build(preorder, inorder,
pre_start + 1, pre_start + 1 + left_size,
in_start, split_point);
root->right = build(preorder, inorder,
pre_start + 1 + left_size, pre_end,
split_point + 1, in_end);

return root;
}
};