是否完全二叉搜索树
题目
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过20的正整数N;第二行给出N个互不相同的正整数,其间以空格分隔。
输出格式:
将输入的N个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出YES,如果该树是完全二叉树;否则输出NO。
输入样例1:
9
38 45 42 24 58 30 67 12 51
输出样例1:
38 45 24 58 42 30 12 67 51
YES
输入样例2:
8
38 24 12 45 58 67 42 51
输出样例2:
38 45 24 58 42 12 67 51
NO
代码
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
int n;
// 完全二叉树标记
int flag3;
struct node {
int value;
struct node *lChild, *rChild;
} *tree;
struct node *insert(struct node *t, int x) {
if (t == NULL) {
// 注意,这里每个都要新申请空间,否则会出错
struct node *tt = (struct node *) malloc(sizeof(struct node));
tt->value = x;
tt->lChild = tt->rChild = NULL;
t = tt;
} else {
if (x < t->value) {
t->rChild = insert(t->rChild, x);
} else {
t->lChild = insert(t->lChild, x);
}
}
return t;
}
void bfs(node *t) {
// 判断是不是第一个元素
int flag = 0;
// 判断该处是否还符合完全二叉树
int flag2 = 1;
if (t == NULL) {
return;
}
queue<node *> q;
q.push(t);
while (!q.empty()) {
node *use = q.front();
q.pop();
if (flag == 0) {
cout << use->value;
flag = 1;
} else {
cout << " " << use->value;
}
if (use->lChild != NULL) {
q.push(use->lChild);
if (flag2 == 0) {
flag3 = 0;
}
} else {
flag2 = 0;
}
if (use->rChild != NULL) {
q.push(use->rChild);
if (flag2 == 0) {
flag3 = 0;
}
} else {
flag2 = 0;
}
}
}
int main() {
cin >> n;
tree = NULL;
flag3 = 1;
for (int i = 1; i <= n; i++) {
int use;
cin >> use;
tree = insert(tree, use);
}
bfs(tree);
cout << endl;
if (flag3) {
cout << "YES\n";
} else {
cout << "NO\n";
}
return 0;
}