Skip to content

Commit 06df7ef

Browse files
committed
Construct Binary Tree from Preorder and Inorder Traversal.
1 parent bae6a92 commit 06df7ef

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/*
2+
Author: Annie Kim, [email protected]
3+
Date: May 16, 2013
4+
Problem: Construct Binary Tree from Preorder and Inorder Traversal
5+
Difficulty: Easy
6+
Source: http://leetcode.com/onlinejudge#question_105
7+
Notes:
8+
Given preorder and inorder traversal of a tree, construct the binary tree.
9+
Note:
10+
You may assume that duplicates do not exist in the tree.
11+
12+
Solution: Recursion.
13+
*/
14+
15+
/**
16+
* Definition for binary tree
17+
* struct TreeNode {
18+
* int val;
19+
* TreeNode *left;
20+
* TreeNode *right;
21+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
22+
* };
23+
*/
24+
25+
class Solution {
26+
public:
27+
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
28+
int N = inorder.size();
29+
return buildTreeRe(preorder, 0, N, inorder, 0, N);
30+
}
31+
32+
TreeNode *buildTreeRe(vector<int> &preorder, int pre_s, int pre_e,
33+
vector<int> &inorder, int in_s, int in_e) {
34+
int N = in_e - in_s;
35+
if (N <= 0) return NULL;
36+
int pos = 0;
37+
while (pos < N && inorder[in_s + pos] != preorder[pre_s]) pos++;
38+
39+
TreeNode *root = new TreeNode(preorder[pre_s]);
40+
root->left = buildTreeRe(preorder, pre_s + 1, pre_s + 1 + pos,
41+
inorder, in_s, in_s + pos);
42+
root->right = buildTreeRe(preorder, pre_s + 1 + pos, pre_e,
43+
inorder, in_s + pos + 1, in_e);
44+
return root;
45+
}
46+
};

0 commit comments

Comments
 (0)