-
Notifications
You must be signed in to change notification settings - Fork 0
/
构建最大二叉树.cpp
66 lines (61 loc) · 1.33 KB
/
构建最大二叉树.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
#include <sstream>
#include <queue>
using namespace std;
void putArray(int* a, vector<int> arr, int left, int right)
{
int index = left;
//组内只有一个元素
if(left == right){
a[left] = arr[left];
return;
}
for(int i=left;i<=right;i++)
{
if(arr[i]>arr[index]){
index = i;
}
}
a[index]=arr[index];
if(index != left){
putArray(a,arr,left,index-1);
}
if(index != right){
putArray(a,arr,index+1,right);
}
}
void levelOrder(int* a, int size)
{
queue<int> q;
q.push(0);
while (!q.empty()) {
int index = q.front();
q.pop();
cout << a[index] << " ";
int left_child = 2 * index + 1;
int right_child = 2 * index + 2;
if (left_child < size) {
q.push(left_child);
}
if (right_child < size) {
q.push(right_child);
}
}
}
int main()
{
string line;
getline(cin, line);
istringstream iss(line);
vector<int> arr;
int num;
while(iss >> num){
arr.push_back(num);
}
int * a = new int[arr.size()];
putArray(a,arr,0,arr.size()-1);
levelOrder(a, arr.size());
delete[] a;
return 0;
}