首页 > 编程语言 > 详细

二叉排序树的查找、插入、删除

时间:2021-07-19 09:41:26      阅读:22      评论:0      收藏:0      [点我收藏+]

include <stdio.h>

include<stdlib.h>

include<stdbool.h>

 typedef char TElemType;
typedef struct BiTree {
	TElemType Data;
	struct BiTree* LChild, * RChild;
}BiTNode, * BiTree;

bool Search(BiTree T, TElemType key, BiTree f, BiTree& p)
{
	if (!T) { p = f; return false; }
	else {
		if (T->Data == key) { p = T; return true; }
		else if (T->Data < key)Search(T->RChild, key, T, p);
		else Search(T->LChild, key, T, p);
	}

}

bool Insert(BiTree& T, TElemType Item)
{
	BiTree p;
	if (!Search(T, Item, NULL, p)) {
		BiTree NewPTree = (BiTree)malloc(sizeof(BiTNode));
		NewPTree->Data = Item;
		NewPTree->LChild = NewPTree->RChild = NULL;
		if (!p) {
			T = NewPTree;
		}
		else {
			if (Item < p->Data)p->LChild = NewPTree;
			else p->RChild = NewPTree;
		}
	}
	else return false;
}

bool Delete(BiTree& T, TElemType Item)
{
	BiTree p;
	Search(T, Item, NULL, p);
	if (!p->LChild) {
		BiTree q = p;
		p = p->RChild;
		free(q);
	}
	else if (!p->RChild) {
		BiTree q = p;
		p = p->RChild;
		free(q);
	}
	else {
		BiTree s = p->LChild, q = p;
		while (s->RChild) {
			q = s;
			s = s->RChild;
		}
		p->Data = s->Data;
		if (q != p)q->RChild = s->LChild;
		else q->LChild = s->LChild;
	}
}

二叉排序树的查找、插入、删除

原文:https://www.cnblogs.com/tzp-empty-hya/p/15028257.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!