二叉查找树(二叉排序树、二叉搜索树)的查找 C/C++

既然名字都叫二叉查找树,是不是肯定得用来查找嘛。

递归和非递归的

//递归查找
BSTNode* RecursionBSTSearch(BSTNode *root, int ele)
{
	if (root == NULL)
	{
		return NULL;
	}

	if (ele == root->data)
	{
		return root;
	}

	if (ele < root->data)
	{
		RecursionBSTSearch(root->lChild,ele);
	}

	RecursionBSTSearch(root->rChild,ele);
}

//非递归查找
BSTNode* noRecursionBSTSearch(BSTNode *root, int ele)
{
	BSTNode *cur = root;
	while (cur != NULL && ele != cur->data)
	{
		if (ele < root->data)
		{
			cur = cur->lChild;
		}
		else
		{
			cur = cur->rChild;
		}
	}
	return cur;
}

 

全部代码:

#include<stdio.h>
#include<stdlib.h>

typedef struct BinarySortTreeNode
{
	int data;  //数据
	struct BinarySortTreeNode * lChild;  //左子树
	struct BinarySortTreeNode * rChild;  //右子树
}BSTNode;

//插入节点
void insertNode(BSTNode *&node, int element)
{
	if (NULL == node)
	{
		node = new BSTNode;
		node->data = element;
		node->lChild = NULL;
		node->rChild = NULL;
	}

	if (element == node->data)
	{
		return;
	}

	if (element < node->data)
	{
		insertNode(node->lChild, element);
	}

	if (element > node->data)
	{
		insertNode(node->rChild, element);
	}
}

//通过 节点数组 初始化二叉查找树
void initBST(BSTNode *&root, int ele[], int len)
{
	if (NULL == ele || 0 == len)
	{
		return;
	}

	for (int i = 0; i < len; i++)
	{
		insertNode(root, ele[i]);
	}
}

//释放二叉树
void freeBST(BSTNode *&root)
{
	if (NULL == root)
	{
		return;
	}

	freeBST(root->lChild);
	freeBST(root->rChild);
	delete root;
	root = NULL;
}

//递归查找
BSTNode* RecursionBSTSearch(BSTNode *root, int ele)
{
	if (root == NULL)
	{
		return NULL;
	}

	if (ele == root->data)
	{
		return root;
	}

	if (ele < root->data)
	{
		RecursionBSTSearch(root->lChild,ele);
	}

	RecursionBSTSearch(root->rChild,ele);
}

//非递归查找
BSTNode* noRecursionBSTSearch(BSTNode *root, int ele)
{
	BSTNode *cur = root;
	while (cur != NULL && ele != cur->data)
	{
		if (ele < root->data)
		{
			cur = cur->lChild;
		}
		else
		{
			cur = cur->rChild;
		}
	}
	return cur;
}

int main()
{
	int eleArr[] = { 5,3,8,7,2,9,1,10,6,4 };
	int len = sizeof(eleArr) / sizeof(eleArr[0]);
	BSTNode *root = NULL;

	initBST(root, eleArr, len);

	int element = 10;
	BSTNode *findNode = RecursionBSTSearch(root,element);
	if (findNode)
	{
		printf("%d - 找到了\n",element);
	}
	else
	{
		printf("%d - 没找到\n", element);
	}
	findNode = noRecursionBSTSearch(root,element);
	if (findNode)
	{
		printf("%d - 找到了\n", element);
	}
	else
	{
		printf("%d - 没找到\n", element);
	}
	freeBST(root);

	system("pause");
	return 0;
}

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值