算法思想:从一棵空树开始,不断将关键字插入到二叉排序树中,最终构造出包含所有关键字元素的二叉排序树。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef char ElemType;
typedef struct BSTNode {
ElemType data;
struct BSTNode* lchild;
struct BSTNode* rchild;
}BSTNode,*BSTree;
void inOrder(BSTree T) {
if (T != NULL) {
inOrder(T->lchild);
printf("%c", T->data);
inOrder(T->rchild);
}
}
void insertKey(BSTNode*& T, ElemType num) {
if (T == NULL) {
BSTNode* pnode = (BSTNode*)malloc(sizeof(BSTNode));
pnode->data = num;
pnode->lchild = NULL;
pnode->rchild = NULL;
T = pnode;
}
else if (T->data > num) {
insertKey(T->lchild, num);
}
else if (T->data < num) {
insertKey(T->rchild, num);
}
}
BSTNode* creatBSTree() {
ElemType num;
BSTNode* T = NULL;
while (scanf("%c", &num) && num != '#') {
insertKey(T, num);
}
return T;
}
int main() {
BSTree T = creatBSTree();
inOrder(T);
return 0;
}