题目
从键盘接受输入,每个节点所含数据元素均为单字符,要完成:
建立一棵二叉链表表示方式存储的二叉排序树,并打印输出对其由大到小遍历结果。
测试数据:输入EFHJBCAGID,符号“@”表示结束字符。
分析
根据二叉排序树的定义可知,对其进行中序遍历可得到由小到大遍历结果,对其进行逆中序遍历即可达到要求
代码
#include <stdio.h>
#include <malloc.h>
#define LEN sizeof(BSTnode)
typedef struct node {
char key;
struct node *lchild,*rchild;
} BSTnode,*BSTree;
//插入结点,并对结点进行判断,确定插入左子树还是右子树
void InsertBST(BSTree *bst,char key) {
BSTree s;
// 若在二叉排序树中不存在关键字等于key的元素则插入该元素
if(*bst==NULL) {
s = (BSTree)malloc(LEN);
s->key = key;
s->lchild = NULL;
s->rchild = NULL;
*bst = s;
} else if(key<(*bst)->key) InsertBST(&((*bst)->lchild),key); //将s插入左子树
else if(key>(*bst)->key) InsertBST(&((*bst)->rchild),key); //将s插入右子树
}
//从键盘输入元素的值,创建相应的二叉排序树
void CreateBst(BSTree *bst) {
char key;
*bst = NULL;
printf("请输入需要排序的字符(以@符号结尾):\n");
scanf("%c",&key);
while(key!='@') {
InsertBST(bst,key);
scanf("%c",&key);
}
}
//逆中序遍历从大到小输出二叉树结点,即先遍历右子树,然后根,最后左子树
void Inorder(BSTree root) {
if(root!=NULL) {
// 先序遍历右子树
Inorder(root->rchild);
// 访问根节点
printf("%c\n",root->key);
// 先序遍历左子树
Inorder(root->lchild);
}
}
int main() {
BSTree root;
CreateBst(&root);
printf("结果序列为:\n");
Inorder(root);
return 0;
}