Fork me on GitHub

Construct Binary Tree from Preorder and Inorder Traversal

Description

https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/

Solution

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.size() == 0) return NULL;
return this->build(preorder, inorder, 0, inorder.size() - 1, 0, preorder.size() - 1);
}

TreeNode* build(vector<int>& preorder, vector<int>& inorder, int inLeft, int inRight, int preLeft, int preRight) {
if (inLeft > inRight || preLeft > preRight) return NULL;
TreeNode* root = new TreeNode(preorder[preLeft]);
int preIndex = preLeft;
int inIndex = inLeft;
while (inIndex <= inRight) {
if (inorder[inIndex] == preorder[preLeft]) {
break;
}
preIndex += 1;
inIndex += 1;
}
root->left = this->build(preorder, inorder, inLeft, inIndex - 1, preLeft + 1, preIndex);
root->right = this->build(preorder, inorder, inIndex + 1, inRight, preIndex + 1, preRight);
return root;
}
};