-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path105. Construct Binary Tree from Preorder and Inorder Traversal.cpp
77 lines (60 loc) · 1.71 KB
/
105. Construct Binary Tree from Preorder and Inorder Traversal.cpp
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
Link: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// Solution 1 Using Recursion
/*
TC = O(n ^ 2)
SC = O(n ^ 2) // recursion stack
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (!preorder.size() || !inorder.size()) {
return NULL;
}
int index = 0
return constructTree(preorder, pos, inorder, 0, inorder.size() - 1);
}
TreeNode* constructTree(vector<int> &preorder, int index, vector<int> &inorder, int low, int high) {
if (low > high) {
return NULL;
}
int i;
for (i = low; i <= high; i++) { // this can be improved by using map
if (inorder[i] == preorder[index]) { // we store all the indexes of inorder and then find
break;
}
}
int index = i - low;
TreeNode* root = new TreeNode(preorder[pos]);
root -> left = constructTree(preorder, index, inorder, il, i - 1);
root -> right = constructTree(preorder, index, inorder, i + 1, ih);
return root;
}
};
// Solution 2
/*
TC =
SC =
*/