pat 1043

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
#include <iostream>
#define MAX 1000
#define NULL 0
using namespace std;
struct node
{
int data;
node* lchild;
node* rchild;
};
int N;
int order[MAX] = {0};
int reorder[MAX] = {0};
void insert(node* &root , int x)
{
if(root == NULL)
{
root = new node;
root->data = x;
root->lchild = root->rchild = NULL;
return ;
}
if(x < root->data)
insert(root->lchild , x);
else
insert(root->rchild , x);
}
node* Create(int data[])//经典建树方法
{
node* root = new node;
root->data = data[0];
root->lchild = root->rchild = NULL;
for(int i = 1; i < N ; ++i)
{
insert(root , data[i]);
}
return root;
}
int index = 0;
void preOrder(node* root)
{
if(root)
{
order[index++] = root->data;
preOrder(root->lchild);
preOrder(root->rchild);
}
}
int reindex = 0;
void preReOrder(node* root)
{
if(root)
{
reorder[reindex++] = root->data;
preReOrder(root->rchild);
preReOrder(root->lchild);
}
}
bool is = true;
void postOrder(node* root)
{
if(root)
{
postOrder(root->lchild);
postOrder(root->rchild);
if(is)
{
cout<<root->data;
is = false;
}
else
cout<<" "<<root->data;
}
}
bool is2 = true;
void RepostOrder(node* root)
{
if(root)
{
RepostOrder(root->rchild);
RepostOrder(root->lchild);
if(is2)
{
cout<<root->data;
is2 = false;
}
else
cout<<" "<<root->data;
}
}
int main()
{
cin>>N;
int i;
int data[MAX];
for(i = 0 ; i < N ; ++i)
{
cin>>data[i];
}
node* root = Create(data);
preOrder(root);
preReOrder(root);
bool flag = true , right = true;
for(i = 0 ; i< N ; ++i)
{
if(order[i] != data[i])
{
flag = false;
break;
}
}
if(!flag)
{
for(i = 0 ; i < N ; ++i)
{
if(reorder[i] != data[i])
{
right = false;
break;
}
}
}
else
right = false;
if(!flag && !right)
cout<<"NO";
else
{
cout<<"YES"<<endl;
if(flag)
{
postOrder(root);
}
else if(right)
{
RepostOrder(root);
}
}
return 0;
}

热评文章