PAT L3-010. 是否完全二叉搜索树
原题链接
简单
作者:
青丝蛊
,
2021-04-23 17:00:09
,
所有人可见
,
阅读 330
#include <bits/stdc++.h>
using namespace std;
struct
{
int data, l, r;
} tree[25];
int p = -1;
vector<int> v;
int build(int root, int x)
{
if (root == -1)
{
tree[++p].data = x;
tree[p].l = tree[p].r = -1;
return p;
}
if (x > tree[root].data) tree[root].l = build(tree[root].l, x);
else tree[root].r = build(tree[root].r, x);
return root;
}
void bfs(int x)
{
cout << tree[x].data;
queue<int> que;
que.push(x);
while (que.size())
{
int t = que.front();
que.pop();
v.push_back(tree[t].l);
v.push_back(tree[t].r);
if (tree[t].l != -1)
{
cout << ' ' << tree[tree[t].l].data;
que.push(tree[t].l);
}
if (tree[t].r != -1)
{
cout << ' ' << tree[tree[t].r].data;
que.push(tree[t].r);
}
}
}
int main()
{
int n;
cin >> n;
int root = -1;
while (n--)
{
int x;
cin >> x;
root = build(root, x);
}
bfs(root);
bool f = 1;
for (int i = 1; i < v.size(); i++)
{
if (v[i] != -1 && v[i - 1] == -1)
{
f = 0;
break;
}
}
if (f) puts("\nYES");
else puts("\nNO");
return 0;
}