-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsolution106.cpp
More file actions
59 lines (51 loc) · 1.31 KB
/
solution106.cpp
File metadata and controls
59 lines (51 loc) · 1.31 KB
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
/**
* Construct Binary Tree from Inorder and Postorder Traversal
*
* cpselvis([email protected])
* September 6th, 2016
*/
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return dfs(inorder, postorder, 0, inorder.size() - 1, 0, postorder.size() - 1);
}
TreeNode* dfs(vector<int> &inorder, vector<int> &postorder, int istart, int iend, int pstart, int pend)
{
if (istart > iend)
{
return NULL;
}
TreeNode *root = new TreeNode(postorder[pend]);
int i;
for (i = istart; i < iend; i ++)
{
if (postorder[pend] == inorder[i])
{
break;
}
}
root -> left = dfs(inorder, postorder, istart, i - 1, pstart, pstart + i - istart - 1);
root -> right = dfs(inorder, postorder, i + 1, iend, pstart + i - istart, pend - 1);
return root;
}
};
int main(int argc, char **argv)
{
int arr1[2] = {2, 1};
int arr2[2] = {2, 1};
vector<int> vec1(arr1 + 0, arr1 + 2);
vector<int> vec2(arr2 + 0, arr2 + 2);
Solution s;
TreeNode *root = s.buildTree(vec1, vec2);
cout << root -> val << endl;
cout << root -> left -> val << endl;
}