-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode.hpp
52 lines (46 loc) · 1.15 KB
/
leetcode.hpp
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
#pragma once
#include <algorithm>
#include <deque>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
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) {}
static TreeNode *construct(vector<int> a) {
TreeNode *root = nullptr;
int n = a.size();
if (n == 0) {
root = nullptr;
return root;
}
deque<TreeNode *> parentStack;
root = new TreeNode(a[0]);
TreeNode *curParent = root;
for (int i = 1; i < n; ++i) {
if (i % 2 == 1) {
if (a[i] != -1) {
curParent->left = new TreeNode(a[i]);
parentStack.push_back(curParent->left);
}
} else {
if (a[i] != -1) {
curParent->right = new TreeNode(a[i]);
parentStack.push_back(curParent->right);
}
curParent = parentStack.front();
parentStack.pop_front();
}
}
return root;
}
};