二叉树之二叉搜索树

简单的实现了一下二叉搜索树的建立与查找,二叉树的前中后序遍历,没啥技术含量纯粹熟悉

一下二叉树的基本操作而已⊙﹏⊙b汗

二叉查找树(Binary Search Tree),或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。

#include<stdio.h>
#include<stdlib.h>
typedef char ElemType;
typedef struct BTree
{
	ElemType data;
	struct BTree *Lchild;
	struct BTree *Rchild;
}BTree,*Tree;
typedef struct root
{
	struct BTree *root;
}root,*Root;
void CreateRoot(Root *TRoot)
{
	if (*TRoot == NULL)
	{
		Root NewNode = (Root)malloc(sizeof(root));
		NewNode->root = NULL;
		*TRoot = NewNode;
	}
}
Tree NewTreeNode(ElemType n)
{
	Tree NewNode = (Tree)malloc(sizeof(BTree));
	NewNode->data = n;
	NewNode->Lchild = NULL;
	NewNode->Rchild = NULL;
	return NewNode;
}
void InsertNode(Root TRoot, ElemType num)
{
	if (TRoot->root == NULL)
	{
		TRoot->root = NewTreeNode(num);
	}
	else
	{
		Tree p = TRoot->root;
		Tree Partner = NULL;
		while (p != NULL)
		{
		//  当循环结束时p==NULL,故用另一个指针Partner保存p的上一个结点。	
			Partner = p;
			if (num < p->data)
			{
				p = p->Lchild;
			}
			else if (num>p->data)
			{
				p = p->Rchild;
			}
			else
			{
				return; // 若插入的元素在二叉树中已存在,则直接返回
			}
		}
		// 继续判断一下待插入值与Parter->data的大小
		if (num < Partner->data)
		{
			Partner->Lchild = NewTreeNode(num);
		}
		else
		{
			Partner->Rchild = NewTreeNode(num);
		}
	}
}
Tree Search(Tree p, ElemType num)
{
	Tree temp = p;
	while (temp != NULL)
	{
		if (num< temp->data)
		{
			temp = temp->Lchild;
		}
		else if (num > temp->data)
		{
			temp = temp->Rchild;
		}
		else
		{
			return temp;
		}
	}
	return NULL;
}
void PreOder(Tree T, int level)
{
	if (T)
	{
		printf("%2d在第%d层 \n", T->data, level);
		PreOder(T->Lchild, level + 1);
		PreOder(T->Rchild, level + 1);
	}
}
void InOder(Tree T, int level)
{
	if (T)
	{
		PreOder(T->Lchild, level + 1);
		printf("%2d在第%d层 \n", T->data, level);
		PreOder(T->Rchild, level + 1);
	}
}
void PostOder(Tree T, int level)
{
	if (T)
	{
		PreOder(T->Lchild, level + 1);
		PreOder(T->Rchild, level + 1);
		printf("%2d在第%d层 \n", T->data, level);
	}
}
int main()
{
	Root TRoot = NULL;
	CreateRoot(&TRoot);
	int A[6] = { 50, 43, 65, 7, 45, 29 };
	for (int i = 0; i < 6; i++)
	{
		InsertNode(TRoot, A[i]);
	}
	printf("前序遍历\n");
	PreOder(TRoot->root, 1);
	printf("\n中序遍历\n");
	InOder(TRoot->root, 1);
	printf("\n后序遍历\n");
	PostOder(TRoot->root, 1);	
	Tree p = Search(TRoot->root, 65);
	if (p)
	{
		printf("找到了\n");
	}
	else
	{
		printf("没到了\n");
	}
	printf("\n\n");
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值