一个二叉排序树的例子
首先看一个常见的二叉排序树的操作,下面的代码包括插入、创建和中序遍历。摘自这里。
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
struct BTreeNode
{
ElemType data;
struct BTreeNode* left;
struct BTreeNode* right;
};
//递归方式插入
void Insert(struct BTreeNode** BST, ElemType x)
{
if (*BST == NULL) //在为空指针的位置链接新结点
{
struct BTreeNode* p = (BTreeNode*)malloc(sizeof(struct BTreeNode));
p->data = x;
p->left = p->right = NULL;
*BST = p;
}
else if (x < (*BST)->data) //向左子树中完成插入运算
Insert(&((*BST)->left), x);
else
Insert(&((*BST)->right), x); //向右子树中完成插入运算
}
//创建二叉搜索树,根据二叉搜索树的插入算法可以很容易实现
void CreateBSTree(struct BTreeNode** BST, ElemType a[], int n)
{
int i;