将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过20的正整数N;第二行给出N个互不相同的正整数,其间以空格分隔。
输出格式:
将输入的N个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出YES,如果该树是完全二叉树;否则输出NO。
数组模拟
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
const int N = 1000100;
int ma[N], tol, n;
int a[N], pos;
int maxx;
void build(int data)
{
int q = 1;
while (1) //找到位置
{
if (ma[q] == 0)break;
if (ma[q] < data)q = q * 2;
else q = q * 2 + 1;
}
ma[q] = data;
maxx = max(q, maxx);
}
int main(int argc, char const *argv[])
{
scanf("%d", &n);
tol = 1;
pos = 1;
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
build(a[i]);
}
int f = 0;
for (int i = 1; i <= maxx; i++) //输出层序遍历
{
if (ma[i] != 0)
{
if (f == 0)printf("%d", ma[i]), f = 1;
else if (f == 1)printf(" %d", ma[i]);
}
}
int flag = 1;
for (int i = 1; i <= n; i++) //判断是否是完全二叉树
{
if (ma[i] == 0)flag = 0;
}
if (flag == 1)printf("\nYES\n");
else printf("\nNO\n");
return 0;
}
结构体写法
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 10010;
struct node
{
int data;
node *l, *r;
}*root;
int tol, f;
struct node *build(int data, struct node *q)
{
if (!q)
{
q = (struct node*)malloc(sizeof(struct node));
q->l = q->r = NULL;
q->data = data;
}
else if (q->data < data)
{
q->l = build(data, q->l);
}
else q->r = build(data, q->r);
return q;
};
void ceng(struct node *q) //层序遍历
{
queue<node*>que;
que.push(q);
int flag = 0;
tol++;
while (!que.empty())
{
struct node *temp = que.front();
que.pop();
if (flag == 0)
{
printf("%d", temp->data);
flag = 1;
}
else printf(" %d", temp->data);
if (temp->l) //每加入一个就让遍历到的数+1,前提是没有遇见空的
{
que.push(temp->l);
if (f == 0)tol++;
}
else f = 1;
if (temp->r)
{
que.push(temp->r);
if (f == 0)tol++;
}
else f = 1;
}
return ;
}
int main()
{
int n;
scanf("%d", &n);
root = NULL;
f = 0;
for (int i = 1; i <= n; i++)
{
int data;
scanf("%d", &data);
root = build(data, root);
}
ceng(root);
if (tol == n)printf("\nYES\n");
else printf("\nNO\n");
return 0;
}