概述
二叉排序树也叫二叉查找树
二叉排序树为什么叫排序树呢?
我的理解是,原本一串乱序的数字,
通过二叉排序树这个特定的逻辑结构
(特定的特定在二叉排序树这个树的性质:
若左子树非空,则左子树上所有结点的值均小于根节点的值;
若右子树非空,则右子树上所有结点的值均大于根节点的值;
左右子树也分别是一个二叉排序树。)
通过这个逻辑结构构建的这颗树,再去通过中序遍历这棵树,
即从根节点的头上一脚踩扁,会惊奇的发现这些数字变得有序了卧槽!
比如说 将 48 23 56 35 12 46 89 依次插入 建立二叉排序树
进行中序遍历后发现 就会变成一串有序的数字:12 23 35 46 48 56 89 妙不可言!
非递归实现
代码实现:
void BST_Insert(BSTree &T,int x)
{
BSTree news=(BSTree) calloc(1,sizeof (BSTNode));
news->data=x;
if(T==NULL)
{
T=news;
}
else
{
BSTree p=T,parent;
while(p)
{
parent=p;
if(x<p->data)
{
p=p->lchild;
}
else if(p->data<x)
{
p=p->rchild;
}
}
if(x<parent->data)
{
parent->lchild=news;
}
else if(x>parent->data)
{
parent->rchild=news;
}
}
}
代码解释:
递归实现
代码实现:
void BST_Insert1(BSTree &T,int x)
{
if(NULL==T)
{
BSTree newtree=(BSTree) calloc(1,sizeof(BSTNode));
newtree->data=x;
T=newtree;
}
else if(x<T->data)
{
BST_Insert1(T->lchild,x);
}
else if(x>T->data)
{
BST_Insert1(T->rchild,x);
}
}
代码解释:
总实现代码
#include <stdio.h>
#include <stdlib.h>
typedef struct BSTNode{
int data;
struct BSTNode *lchild;
struct BSTNode *rchild;
}BSTNode,*BSTree;
//非递归插入
void BST_Insert(BSTree &T,int x)
{
BSTree news=(BSTree) calloc(1,sizeof (BSTNode));
news->data=x;
if(T==NULL)
{
T=news;
}
else
{
BSTree p=T,parent;
while(p)
{
parent=p;
if(x<p->data)
{
p=p->lchild;
}
else if(p->data<x)
{
p=p->rchild;
}
}
if(x<parent->data)
{
parent->lchild=news;
}
else if(x>parent->data)
{
parent->rchild=news;
}
}
}
//创建树
void Creat_BST(BSTree &T,int *a,int len)
{
for(int i=0;i<len;i++)
{
BST_Insert(T,a[i]);
}
}
//递归插入
void BST_Insert1(BSTree &T,int x)
{
if(NULL==T)
{
BSTree newtree=(BSTree) calloc(1,sizeof(BSTNode));
newtree->data=x;
T=newtree;
}
else if(x<T->data)
{
BST_Insert1(T->lchild,x);
}
else if(x>T->data)
{
BST_Insert1(T->rchild,x);
}
}
//创建树
void Creat_BST1(BSTree &T,int *a,int len)
{
for(int i=0;i<len;i++)
{
BST_Insert1(T,a[i]);
}
}
int main() {
BSTree T=NULL;
int a[7]={48,23,56,35,12,46,89};
Creat_BST(T,a,7);
//Creat_BST1(T,a,7);
return 0;
}
调试结果
通过调试后,树T的结构如下