1
二叉搜索树的层次遍历(10分)
题目内容:
二叉搜索树在动态查表中有特别的用处,一个无序序列可以通过构造一棵二叉搜索树变成一个有序序列,
构造树的过程即为对无序序列进行排序的过程。每次插入的新的结点都是二叉搜索树上新的叶子结点,在进行
插入操作时,不必移动其它结点,只需改动某个结点的指针,由空变为非空即可。
这里,我们想探究二叉树的建立和层次输出。
输入格式:
只有一行,包含若干个数字,中间用空格隔开。(数字可能会有重复,对于重复的数字,只计入一个)
输出格式:
输出一行,对输入数字建立二叉搜索树后进行按层次周游的结果。
输入样例:
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
时间限制:500ms内存限制:32000kb
二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。
二叉搜索树的插入是个标准的递归算法,中序遍历借助队列完成,这里用数组指针模拟了一个队列
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode
{
ElementType Data;
BinTree Left;
BinTree Right;
};
BinTree Insert(BinTree BST, ElementType X);
void LevelorderTraversal(BinTree BT);
int main()
{
BinTree BST = NULL;
int temp;
char c;
while (1)
{
scanf_s("%d", &temp);
BST = Insert(BST, temp);
c = getchar();
if (c != ' ')
break;
}
LevelorderTraversal(BST);
system("pause");
return 0;
}
/* 你的代码将被嵌在这里 */
BinTree Insert(BinTree BST, ElementType X)
{
if (!BST)
{
BST = (BinTree)malloc(sizeof(struct TNode));
BST->Data = X;
BST->Left = BST->Right = NULL;
}
else
{
if (X < BST->Data)
{
BST->Left = Insert(BST->Left, X); // 递归插入左子树
}
else if (X > BST->Data)
{
BST->Right = Insert(BST->Right, X); // 递归插入右子树
}
}
return BST;
}
void LevelorderTraversal(BinTree BT)
{
if (!BT)
return;
int flag = 0; // 控制输出格式
BinTree queue[100];
BinTree temp;
int front = 0, rear = 0;
queue[rear++] = BT; // 当前节点入队
while (front != rear) // 当队列非空的情况
{
temp = queue[front++];
if (!flag)
{
printf("%d", temp->Data);
flag = 1;
}
else
{
printf(" %d", temp->Data);
}
if (temp->Left)
queue[rear++] = temp->Left;
if (temp->Right)
queue[rear++] = temp->Right;
}
}