二叉查找树的层序遍历
Case Time Limit: 300 MS (Others) / 1500 MS (Java) Case Memory Limit: 256 MB (Others) / 512 MB (Java)
Accepted: 37 Total Submission: 50
Problem Description
给定一棵二叉查找树(BST)的插入序列,输出它的层序遍历序列。
Input
第一行给出一个正整数N(1<=N<=10^5),表示二叉查找树的结点个数。
第二行包含N个唯一的整数,每个数都在[0,10^9]范围内。
Output
输出一行用空格隔开的二叉查找树的层序遍历序列。行末不允许有多余的空格。
Sample Input
5
3 1 2 4 5
Sample Output
3 1 4 2 5
Author
lgn
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
typedef struct tnode
{
int val;
struct tnode * lchild;
struct tnode * rchild;
}TNode, *PTNode;
using namespace std;
const int MaxN = 100010;
void Insert(PTNode &root,int value)
{
if (!root)
{
root = new TNode;
root->val = value;
root->lchild = root->rchild = nullptr;
}
else if (value < root->val)
Insert(root->lchild, value);
else
Insert(root->rchild, value);
}
PTNode CreateTree(int data[], int n)
{
PTNode root = nullptr;
for (int i = 0; i < n; ++i)
Insert(root, data[i]);
return root;
}
void Level(PTNode root)
{
if (!root)return;
queue<PTNode> que; que.push(root);
while (que.size())
{
PTNode node = que.front(); que.pop();
if (node->lchild)que.push(node->lchild);
if (node->rchild)que.push(node->rchild);
cout << node->val;
if (que.size())
cout << " ";
delete node;
}
}
int main()
{
#ifdef _DEBUG
freopen("data.txt", "r+", stdin);
#endif // _DEBUG
std::ios::sync_with_stdio(false);
int n, data[MaxN];
cin >> n;
for (int i = 0; i < n; ++i)
cin >> data[i];
PTNode root = CreateTree(data, n);
Level(root);
return 0;
}