@【数据结构】(二叉排序树)

@【数据结构】(二叉排序树)

创建一二叉排序树,然后利用该二叉排序树实现数据的查询

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#define MAX 100
using namespace std;

typedef struct Node
{
	int data;
	struct Node *lchild, *rchild;
}BiTNode, *BiTree;

bool search(BiTree T, int key, BiTree parent, BiTree &p)
{
	if (!T)   //树为空,则查找不成功
	{
		p = parent;
		return false;
	}
	else
	{
		if (key == T->data)
		{
			p = T;
			return true;
		}
		else if (key < T->data)
			return search(T->lchild, key, T, p);
		else
			return search(T->rchild, key, T, p);
	}
}
bool insert(BiTree &T, int key)
{
	BiTree p;
	if (!search(T, key, NULL, p))     //查找失败时,插入
	{
		BiTree N = (BiTree)malloc(sizeof(BiTNode));
		N->data = key; 
		N->lchild = NULL;
		N->rchild = NULL;
		if (!p)
			T = N;     //树空时
		else if (key < p->data)
			p->lchild = N;    // 作为左孩子插入
		else
			p->rchild = N;
		return true;
	}
	else
		return false;
}
BiTree create(int *a, int len)
{
	BiTree T = NULL;
	int i;
	for (i = 0; i < len; i++)
		insert(T, a[i]);
	return T;
}
void inorder(BiTree T)
{
	if (T)
	{
		if (T->lchild)
			inorder(T->lchild);
		cout << T->data << "   ";
		if (T->rchild)
			inorder(T->rchild);
	}
}
BiTree search1(BiTree T, int x)
{
	if (!T || T->data == x)
		return T;
	else  if (x < T->data)
		return search1(T->lchild, x);    //左子树中递归查找
	else
		return search1(T->rchild, x);    //右子树中递归查找

}
void main()
{
	int len, a[100];
	BiTree T;
	cout << "请输入元素序列大小:";
	cin >> len;   
	cout << "输入互不相等的元素序列:" << endl;
		for (int i = 0; i < len; i++)
		cin >> a[i];
	cout << "创建二叉排序树" << endl;
	T = create(a, len);
	cout << "中序遍历创建的二叉排序树,得到有序结果为:" << endl;
	inorder(T); cout << endl;
	int x;
	cout << "请输入要查找的数:";
	cin >> x;
	if (search1(T, x))
		cout << "查找成功";
	else
		cout << "查无此数";
	cout << endl;
	system("pause");
}


测试:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值