二叉排序树的实现

typedef struct BTNode {
	KeyType Key;
	InfoType data;
	struct BTNode* lchild, * rchild;
}*BSTNode,BSTnode;

1.编写SearchBST(T, key)与InsertBST(T, key)的伪代码,并实现

伪代码:

void SearchBST(BSTNode T,int key)
{
	if(T为空||T的关键字==key)
		return;
	if(key<T的关键字)
		SearchBST(T->lchild, key);
	else
		SearchBST(T->rchild, key);
}
void InsertBST(BSTNode &T,int key)
{
	if(T为空)
	{
		T=new BiTreeNode();
		将key存入T节点中;
		T的左右孩子为空;
        return;
	}
	else if(key等于T的关键字)
		return;
	else if(key小于T的关键字)
		InsertBST(T->lchild, key);
	else
		InsertBST(T->rchild, key);
}

代码

void SearchBST(BSTNode T, int key)
{
	if (T == NULL || T->Key == key)
		return;
	else if (key < T->Key)
		SearchBST(T->lchild, key);
	else
		SearchBST(T->rchild, key);
}
void InserBST(BSTNode T, int key)
{
	if (T == NULL)
	{
		T = new BSTnode();
		T->Key = key;
		T->lchild = T->rchild = NULL;
		return;
	}
	else if (T->Key == key)
		return;
	else if (key < T->Key)
		InserBST(T->lchild, key);
	else
		InserBST(T->rchild, key);
}

2. 编写CreateBST(T)的伪代码实现从控制台输入创建BST树。最后使用代码实现。使用“50 30 80 20 40 90 10 25 35 85 23 88”创建BST,并中序输出该BST

伪代码

void CreateBST(T)
{
	int a[100],j;
	for(int i=0;a[i];i++)
		cin>>a[i];
	while(j小于i)
	{
		调用插入函数InserBST(T,a[i]);
		j++;
	}
	return;
}

代码

void CreateBST(BSTNode &T)
{
	int a[100], j, i, n;
	j = i = 0;
	cin >> n;
	for (i = 0; i < n; i++)
		cin >> a[i];
	while (j<i)
	{
		InserBST(T, a[j]);
		j++;
	}
	return;
}

运行输出

3. 编写DeleteBST(T, key)的伪代码实现从T中删除关键字key。如果无法编写出来,请写出在BST中删除关键字key所需注意的事项。

伪代码

DeleteBST(T, key)
{
	if(T为空)
		return;
	if(key<T->Key)
		DeleteBST(T->lchild,key);
	else if(key>T->Key)
		DeleteBST(T->rchild,key);
	else
	{
		调用Delete(T)删除T节点;
		return;
	}
}
Delete(p)
{
    BSTNode q;
    if(p的右子树为空)
    {
        q=p;
        p=p->lchild;
        释放q节点;
    }
    else if(p的左子树为空)
    {
		q=p;
        p=p->rchild;
        释放q节点;
    }
    else
        调用Delete1(p,p->lchild)删除既有左子树又有右子树的节点p
}
Delete1(p,r)
{
    BSTNode q;
    if(r的右子树为空)
        递归调用Delete1(p,r->rchild)找到前驱节点;
    else
    {
        p->Key=r->Key;
        q=r;r=r->lchild;
        释放q节点;
    }
}

4. 使用代码实现DeleteBST(T, key)

void DeleteBST(BSTNode &T,int key)
{
	if(T==NULL)
		return;
	if(key<T->Key)
		DeleteBST(T->lchild,key);
	else if(key>T->Key)
		DeleteBST(T->rchild,key);
	else
	{
		Delete(T);
		return;
	}
}
void Delete(BSTNode &p)
{
    BSTNode q;
    if(p->rchild==NULL)
    {
        q=p;
        p=p->lchild;
        free(q);
    }
    else if(p->lchild==NULL)
    {
		q=p;
        p=p->rchild;
        free(q);
    }
    else
        Delete1(p,p->lchild);
}
void Delete1(BSTNode &p,BSTNode &r)
{
    BSTNode q;
    if(r->rchild==NULL)
        Delete1(p,r->rchild);
    else
    {
        p->Key=r->Key;
        q=r;r=r->lchild;
        free(q);
    }
}
posted @ 2020-04-19 20:58  awwman  阅读(218)  评论(0编辑  收藏  举报