数据结构-二分搜索树14

二分搜索树 Binary Search Tree

性质:

a. 二分搜索树是二叉树

b.二分搜索树的每一个节点的值:
       大于其左子树的所有节点的值
       小于其右子树的所有节点的值

c.每一颗子树也是二分搜索树

e.存储的元素必须具有可比较性(二分搜索树的一个缺点)

如下图:
在这里插入图片描述
接下来就用代码实现它的元素添加和查找:

struct TreeNode 
{
	int ndata;
	char buf[24];
	struct TreeNode *lchild;
	struct TreeNode *rchild;
};

int ncount = 100;
void InsertTreeNode(TreeNode *&m_root, int ndata)
{
	if (m_root == nullptr)
	{
		struct TreeNode *temp = new struct TreeNode;
		sprintf(temp->buf, "Ty%d", ncount++);
		temp->lchild = NULL;
		temp->rchild = NULL;
		temp->ndata = ndata;
		m_root = temp;
	}
	else if (m_root->ndata>ndata)
	{
		//根大于待插入的节点,则往左插
		InsertTreeNode(m_root->lchild, ndata);

	}
	else if (m_root->ndata<ndata)
	{
		//根大于待插入的节点,则往右插
		InsertTreeNode(m_root->rchild, ndata);
	}
	else
	{
		cout << "不能重复插:" << ndata << endl;
	}



}

void inorder(TreeNode *m_root)
{
	if (m_root)
	{
		cout << "ndata:" << m_root->ndata << " " << "buf:" << m_root->buf << endl;
		inorder(m_root->lchild);
		inorder(m_root->rchild);
	}
	
}


void clearTree(TreeNode *&m_root)
{
	if (m_root)
	{
		cout << "释放:" << m_root->ndata << endl;
		TreeNode *lchild = m_root->lchild;
		TreeNode *rchild = m_root->rchild;
		delete m_root;
		m_root = nullptr;
		clearTree(lchild);
		clearTree(rchild);
	}

}

void clearTree2(TreeNode *&m_root)
{
	if (m_root == nullptr)
	{
		return;
	}
	clearTree(m_root->lchild);
	clearTree(m_root->rchild);
	cout << "释放:" << m_root->ndata << " "<<m_root->buf<<endl;
	delete m_root;
	m_root = nullptr;
	
	
}

int nx = 0;
TreeNode *SearchTreeNodeByData(TreeNode *m_root, int ndata)
{
	nx++;
	if (!m_root)
	{
		return nullptr;
	}
	if (m_root->ndata == ndata)
	{
		return m_root;

	}
	else
	{
		if (ndata<m_root->ndata)
		{
			return SearchTreeNodeByData(m_root->lchild, ndata);
		}
		else
		{
			return SearchTreeNodeByData(m_root->rchild, ndata);
		}

	}
}

void main()
{
	TreeNode *root = nullptr;
	InsertTreeNode(root, 28);
	InsertTreeNode(root, 16);
	InsertTreeNode(root, 30);
	InsertTreeNode(root, 13);
	InsertTreeNode(root, 22);
	InsertTreeNode(root, 29);
	InsertTreeNode(root, 42);
	

	inorder(root);
	cout << endl;

	
	int ndata = 38;
	cout << "我将要查找" << ndata << endl;
	TreeNode *findnode = SearchTreeNodeByData(root, ndata);
	if (findnode == nullptr)
	{
		cout << "没有发现\n";
	}
	else
	{
		cout << "一共搜索了" << nx << "次!" << endl;
		cout << "找到值为" << findnode->ndata << "的节点,并且它的buf为"<<findnode->buf<<endl;
	}

	cout << endl;
	cout << "注意了啊,Ty要释放了!\n";
	clearTree(root);
	system("pause");
}

结果:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发如雪-ty

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值