-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIs_It_a_Binary_Search_Tree.cpp
142 lines (133 loc) · 2.45 KB
/
Is_It_a_Binary_Search_Tree.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
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
#include <iostream>
struct bnode
{
int date;
bnode *lchild, *rchild;
};
int a[1010];
int flag = 0;
using std::cin;
using std::cout;
bnode *build(int p, int q)
{
if (p == q - 1)
{
bnode *b = new bnode;
b->date = a[p];
b->lchild = NULL;
b->rchild = NULL;
return b;
}
int temp = a[p];
int j;
for (int i = p + 1; i < q; i++)
{
if (a[i] >= temp)
{
j = i;
break;
}
}
for (int i = j; i < q; i++)
{
if (a[i] < temp)
{
flag = 1;
return NULL;
}
}
bnode *b = new bnode;
b->date = a[p];
if (p + 1 == j)
b->lchild = NULL;
else
b->lchild = build(p + 1, j);
if (j == q)
b->rchild = NULL;
else
b->rchild = build(j, q);
return b;
}
bnode *build1(int p, int q)
{
if (p == q - 1)
{
bnode *b = new bnode;
b->date = a[p];
b->lchild = NULL;
b->rchild = NULL;
return b;
}
int temp = a[p];
int j;
for (int i = p + 1; i < q; i++)
{
if (a[i] < temp)
{
j = i;
break;
}
}
for (int i = j; i < q; i++)
{
if (a[i] >= temp)
{
flag = 1;
return NULL;
}
}
bnode *b = new bnode;
b->date = a[p];
if (p + 1 == j)
b->lchild = NULL;
else
b->lchild = build1(p + 1, j);
if (j == q)
b->rchild = NULL;
else
b->rchild = build1(j, q);
return b;
}
int postorder(bnode *root)
{
if (root->lchild != NULL)
postorder(root->lchild);
if (root->rchild != NULL)
postorder(root->rchild);
cout << root->date << " ";
return 0;
}
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
bnode *root = build(0, n);
if (flag == 0)
{
cout << "YES" << std::endl;
if (root->lchild != NULL)
postorder(root->lchild);
if (root->rchild != NULL)
postorder(root->rchild);
cout << root->date;
return 0;
}
flag = 0;
root = build1(0, n);
if(flag==0)
{
cout << "YES" << std::endl;
if (root->lchild != NULL)
postorder(root->lchild);
if (root->rchild != NULL)
postorder(root->rchild);
cout << root->date;
return 0;
}
cout << "NO";
return 0;
}