输入格式:
输入第一行给出一个不超过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<iostream>
#include<queue>
using namespace std;
struct Node
{
int key;
Node *leftChild, *rightChild;
};
bool Insert(Node *&root, int key)//插入关键字
{
if (root == nullptr)//如果为空,证明找到插入位置
{
root = new Node;
root->leftChild = nullptr;
root->rightChild = nullptr;
root->key = key;
return true;
}
else
{
if (key == root->key) return false;
else if (key < root->key)
{
return Insert(root->rightChild, key);
}
else if (key > root->key)
return Insert(root->leftChild, key);
}
}
void CreateTree(Node *&root, int key[], int n) //创建二叉搜索树
{
root = nullptr;
for (int i = 0; i < n; ++i) Insert(root, key[i]);
}
bool IsComTree(Node *root)//判断是否为完全二叉树
{
if (root == nullptr) return false;
queue<Node*> q;
q.push(root);
while (!q.empty())
{
Node* cur = q.front();
if (cur->leftChild&&cur->rightChild)
{
q.pop();
q.push(cur->leftChild);
q.push(cur->rightChild);
}
if (!cur->leftChild&&cur->rightChild) return false;
if ((cur->leftChild&&cur->rightChild == nullptr) || (cur->leftChild == nullptr && cur->rightChild == nullptr))
{
q.pop();
while (!q.empty())
{
cur = q.front();
if (cur->leftChild == nullptr&&cur->rightChild == nullptr) q.pop();
else return false;
}
return true;
}
}
return true;
}
void Level(Node *root,int n)
{
int cnt = 1;
queue<Node*> Q;//创建一个存储队列
Node *cur;
if (root == nullptr) return;//空树返回
Q.push(root);
while (!Q.empty())
{
cur = Q.front();
Q.pop();
if (cur->leftChild)Q.push(cur->leftChild);
if (cur->rightChild)Q.push(cur->rightChild);
if (cnt == n) cout << cur->key << endl;
else cout << cur->key << " ";
cnt++;
}
}
int main()
{
Node* root;
int n; cin >> n;
int *key = new int[n];
for (int i = 0; i < n; ++i) cin >> key[i];
CreateTree(root, key, n);
Level(root, n);
if (IsComTree(root)) cout << "YES" << endl;
else cout << "NO" << endl;
delete[]key;
return 0;
}