将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过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
常规建树,由于需要判断是否是完全二叉树,所以在 Tree 节点中加一个 id 编号,如果 id 都小于 n,说明是完全二叉树,否则不是,建树的时候,标记 id,最后层次遍历输出即可
#include<iostream>
#include<bits/stdc++.h>
#include<string>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<deque>
#include<unordered_set>
#include<unordered_map>
#include<cctype>
#include<algorithm>
#include<stack>
using namespace std;
bool flag = true;
bool flag2 = true;
int n;
typedef struct Node {
int val;
int id;
struct Node *left, *right;
}Node, *Tree;
Tree create(Tree tree, int val, int num) {
if (num > n) {
flag2 = false;
}
if (tree == NULL) {
tree = new Node();
tree->val = val;
tree->id = num;
tree->left = tree->right = NULL;
return tree;
}
if (val > tree->val) {
tree->left = create(tree->left, val, num * 2);
} else {
tree->right = create(tree->right, val, num * 2 + 1);
}
return tree;
}
void cengciOrder(Tree tree) {
queue<Tree> qu;
if (tree == NULL) {
return;
}
qu.push(tree);
while (!qu.empty()) {
Tree t = qu.front();
qu.pop();
if (flag) {
cout << t->val;
flag = false;
} else {
cout << " " << t->val;
}
if (t->left != NULL) {
qu.push(t->left);
}
if (t->right != NULL) {
qu.push(t->right);
}
}
}
int main() {
cin >> n;
Tree tree = NULL;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
tree = create(tree, x, 1);
}
cengciOrder(tree);
cout << endl;
cout << (flag2 == true ? "YES" : "NO");
return 0;
}