-
Notifications
You must be signed in to change notification settings - Fork 481
/
0105.cpp
45 lines (43 loc) · 1.28 KB
/
0105.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
#include <iostream>
#include <vector>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
static int x = []() {std::ios::sync_with_stdio(false); cin.tie(0); return 0; }();
class Solution
{
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
{
if (preorder.empty() or inorder.empty()) return nullptr;
TreeNode* root = new TreeNode(preorder[0]);
vector<TreeNode*> stack = {root};
unsigned int k = 0;
for (unsigned int i = 1; i < preorder.size(); ++i)
{
auto parent = *stack.rbegin();
if (parent->val != inorder[k])
{
parent->left = new TreeNode(preorder[i]);
stack.push_back(parent->left);
}
else
{
while (!stack.empty() and (*stack.rbegin())->val == inorder[k])
{
parent = *stack.rbegin();
stack.pop_back();
++k;
}
parent->right = new TreeNode(preorder[i]);
stack.push_back(parent->right);
}
}
return root;
}
};