这里的二叉排序树的创建是根据课本上写的,其中掺杂了递归思想,之前的写的二叉树的创建是为非递归的方法https://blog.youkuaiyun.com/qq_43402544/article/details/109228383。
完整代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct//关键字结构体
{
int key;//关键字项
int otherinfo;//其他数据域
}ElemType;//每个节点的数据域的类型
typedef struct BSTNode//二叉树结构体
{
ElemType data;//每个节点的数据域包括关键字项和其他数据项
struct BSTNode *lchild,*rchild;//左右孩子指针
}BSTNode,*BSTree;
void InitTree(BSTree &T)//初始化二叉排序树
{
T = (BSTNode*)malloc(sizeof(BSTNode));//创建一个头结点
T->data.key = NULL;
T->lchild = T->rchild = NULL;//头结点指针域和数据域都NULL
}
void InsertTree(BSTree &T,int e)//二叉排序树的插入
{
if(!T)//找到插入位置,递归结束
{
BSTree S;
S = (BSTNode *)malloc(sizeof(BSTNode));//创建一个结点
S->data.key = e;//新结点的数据置为e
S->lchild = S->rchild = NULL;//新结点设置为叶子结点
T = S;//把新结点S接到已找到的插入位置
}
else if(e<T->data.key)
InsertTree(T-></