二叉搜索树的层次遍历
题目内容:二叉搜索树在动态查表中有特别的用处,一个无序序列可以通过构造一棵二叉搜索树变成一个有序序列,构造树的过程即为对无序序列进行排序的过程。每次插入的新的结点都是二叉搜索树上新的叶子结点,在进行插入操作时,不必移动其它结点,只需改动某个结点的指针,由空变为非空即可。
这里,我们想探究二叉树的建立和层次输出。
输入格式:
只有一行,包含若干个数字,中间用空格隔开。(数字可能会有重复,对于重复的数字,只计入一个)
输出格式:
输出一行,对输入数字建立二叉搜索树后进行按层次周游的结果。
输入样例:
51 45 59 86 45 4 15 76 60 20 61 77 62 30 2 37 13 82 19 74 2 79 79 97 33 90 11 7 29 14 50 1 96 59 91 39 34 6 72 7
输出样例:
51 45 59 4 50 86 2 15 76 97 1 13 20 60 77 90 11 14 19 30 61 82 96 7 29 37 62 79 91 6 33 39 74 34 72
#include <iostream>
#include <algorithm>
#include <deque>
using namespace std;
struct treepoint
{
int info;
treepoint* leftchild;
treepoint* rightchild;
treepoint()
{
leftchild = NULL;
rightchild = NULL;
info = 0;
}
};
void insert(int n, treepoint* root)
{
if (n > root->info)
{
if (root->rightchild == NULL)
{
root->rightchild = new treepoint;
root->rightchild->info = n;
return;
}
insert(n, root->rightchild);
}
else
{
if (root->leftchild == NULL)
{
root->leftchild = new treepoint;
root->leftchild->info = n;
return;
}
insert(n, root->leftchild);
}
}
deque<treepoint*> s;
void my_print(treepoint* root)
{
cout << root->info;
if (root->leftchild != NULL)
s.push_back(root->leftchild);
if (root->rightchild != NULL)
s.push_back(root->rightchild);
if (!s.empty())
{
cout << " ";
treepoint* next = s.front();
s.pop_front();
my_print(next);
}
}
int visited[1000] = { 0 };
int main()
{
int n;
cin >> n;
treepoint* root = new treepoint;
root->info = n;
visited[n] = 1;
while (cin >> n)
{
if (visited[n] == 1)
continue;
visited[n] = 1;
insert(n, root);
}
my_print(root);
cout << endl;
return 0;
}