-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path106.cpp
More file actions
39 lines (35 loc) · 1.07 KB
/
106.cpp
File metadata and controls
39 lines (35 loc) · 1.07 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
#include "vector"
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Problem106{
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder){
post = postorder;
in = inorder;
curr = inorder.size()-1;
return recursive(0, postorder.size()-1);
}
TreeNode* recursive(int left, int right){
if (left > right)
return NULL;
int i = 0;
while(in[i] != post[curr])
i++;
curr--;
TreeNode* node = new TreeNode(in[i]);
node->right = recursive(i+1, right);
node->left = recursive(left, i-1);
return node;
}
private:
int curr;
vector<int> post, in;
};