7-2 是否完全二叉搜索树(30 分)
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过20的正整数N
;第二行给出N
个互不相同的正整数,其间以空格分隔。
输出格式:
将输入的N
个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出YES
,如果该树是完全二叉树;否则输出NO
。
摒弃用数组的陋习
#include <bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
const int maxn = 4400010 + 10;
struct Tree
{
int v;
} t[maxn<<2];
//int s1[maxn<<2];
//int s2[maxn<<2];
int n;
int m;
void Insert(int z)
{
int x = 1, y = 1;
while(t[x].v != INF)
{
y = x;
if(t[x].v >= z)
{
x = x << 1 | 1;
}
else
{
x = x << 1;
}
}
if(t[y].v == INF)
{
t[1].v = z;
}
else if(z < t[y].v)
{
t[y<<1|1].v = z;
}
else
{
t[y<<1].v = z;
}
}
//void PreOrder1(int i)
//{
// if(t[i].v != INF) s1[i] = t[i].v;
// else return;
// PreOrder1(i<<1);
// PreOrder1(i<<1|1);
//}
//void PreOrder2(int i)
//{
// if(t[i].v != INF) s2[i] = t[i].v;
// else return;
// PreOrder2(i<<1);
// PreOrder2(i<<1|1);
//}
bool LevelOrder()
{
queue<int>que;
que.push(1);
if(t[1].v == INF)
{
cout << endl;
return true;
}
bool check = false;
while(!que.empty())
{
int q = que.front();
que.pop();
if(!check)
{
check = !check;
cout << t[q].v;
}
else
{
cout << " " << t[q].v;
}
if(t[q << 1].v == INF && t[q << 1 | 1].v == INF) break;
if(t[q << 1].v != INF)
{
que.push(q << 1);
}
if(t[q << 1 | 1].v != INF)
{
que.push(q << 1 | 1);
}
}
while(!que.empty())
{
int q = que.front();
que.pop();
if(que.empty())
{
if(!check)
{
cout << t[q].v;
check = !check;
}
else
{
cout << " " << t[q].v;
}
}
else
{
if(!check)
{
cout << t[q].v;
check = !check;
}
else
{
cout << " " << t[q].v;
}
}
}
cout << endl;
while(!que.empty())
{
que.pop();
}
if(t[1].v == INF) return true;
que.push(1);
bool flag = false;
while(!que.empty())
{
int q = que.front();
que.pop();
if(t[q].v != INF)
{
if(flag)
return false;
que.push(q << 1);
que.push(q << 1 | 1);
}
else
flag = true;
}
return true;
}
int main()
{
cin >> n;
{
for(int k = 0 ; k < maxn * 4 ; k++) t[k].v = INF;
// for(int k = 0 ; k < maxn * 4 ; k++) s1[k] = INF;
int x;
for(int i = 0 ; i < n ; i++)
{
cin >> x;
Insert(x);
}
if(LevelOrder())
{
cout << "YES" << endl;
}
else
{
cout << "NO" << endl;
}
}
return 0;
}