-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
31 lines (29 loc) · 1.09 KB
/
Solution.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
#include<bits/stdc++.h>
using namespace std;
/**
* Definition for a binary tree node.
* 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 Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if(postorder.empty()){
return nullptr;
}
int left_size = ranges::find(inorder, postorder.back()) - inorder.begin();
vector<int> in1(inorder.begin(), inorder.begin() + left_size);
vector<int> in2(inorder.begin() + left_size + 1, inorder.end());
vector<int> post1(postorder.begin(), postorder.begin() + left_size);
vector<int> post2(postorder.begin() + left_size, postorder.end() - 1);
TreeNode* left = buildTree(in1, post1);
TreeNode* right = buildTree(in2, post2);
return new TreeNode(postorder.back(), left, right);
}
};