-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.cpp
More file actions
48 lines (43 loc) · 1.11 KB
/
test.cpp
File metadata and controls
48 lines (43 loc) · 1.11 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
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* buildTreeFromPreOrder(const vector<int>& preOrder, int& index) {
if(preOrder.empty() || index >= preOrder.size()) {
return nullptr;
}
if(preOrder[index] == 0) {
++ index;
return nullptr;
}
TreeNode* root = new TreeNode(preOrder[index]);
++ index;
root->left = buildTreeFromPreOrder(preOrder, index);
root->right = buildTreeFromPreOrder(preOrder, index);
return root;
}
};
void getPreOrder(TreeNode* root) {
if(root == nullptr) {
cout << 0 << " ";
return;
}
cout << root->val << " ";
getPreOrder(root->left);
getPreOrder(root->right);
}
int main() {
Solution solution;
int index = 0;
vector<int> preOrder = {1,5,8,0,0,0,6,0,0};
TreeNode* result = solution.buildTreeFromPreOrder(preOrder, index);
getPreOrder(result);
cout << endl;
return 0;
}