二叉排序树

一、定义

二叉排序树又称作二叉查找树,它是一种对排序和查找都很有用的特殊二叉树。二叉排序树或者是一棵空树,或者是具有下列性质的二叉树:
(1)若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
(2)若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
(3)它的左、右子树也分别为二叉排序树.
由以上定义可得出:中序遍历一棵二叉树时可以得到一个结点值递增的有序序列

二、二叉排序树的创建、查找、插入


	//-----------二叉排序树的二叉链表存储形式-------------------
	typedef int KeyType,InfoType;

	//数据元素定义
	typedef struct
	{
	    KeyType key;            //关键字域
	    InfoType otherinfo;     //其他域
	} ElemType;
	//结点
	typedef struct BSTNode
	{
	    ElemType data;
	    struct BSTNode *lchild,*rchild;//左右子树
	} BSTNode,*BSTree;
	//插入二叉排序树
	void InsertBST(BSTree &T,ElemType e)
	{
	    if(!T)
	    {
	        BSTree S = new BSTNode;
	        S->data = e;
	        S->lchild=S->rchild=NULL;
	        T=S;
	    }
	    else if(T->data.key>e.key)
	    {
	        InsertBST(T->lchild,e);
	    }
	    else if(T->data.key<e.key)
	    {
	        InsertBST(T->rchild,e);
	    }
	}
	#define ENDFLAG 0
	//创建二叉排序树
	void CreateBSTree(BSTree &T)
	{
	    ElemType e;
	    T=NULL;
	    cout << "输入key和value,0结束" << endl;
	    cin >> e.key >> e.otherinfo;
	    int i = 0;
	    while(e.key!=ENDFLAG)
	    {
	        i++;
	        InsertBST(T,e);
	        cin >> e.key >> e.otherinfo;
	    }
	    cout << "创建成功,共有" << i << "个元素" << endl;
	}
	
	
	//查找二叉排序树
	ElemType SearchBST(BSTree T,KeyType key)
	{
	    if(T)
	    {
	        if(T->data.key==key)
	        {
	            return T->data;
	        }
	        else if(T->data.key>key)
	        {
	            return SearchBST(T->lchild,key);
	        }
	        else if(T->data.key<key)
	        {
	            return SearchBST(T->rchild,key);
	        }
	    }
	    else
	    {
	        ElemType e;
	        e.key=-1;
	        return e;
	    }
	
	}
原文地址:https://www.cnblogs.com/HenuAJY/p/11007393.html