王道C语言 OJ

Description

读取10个元素 87 7 60 80 59 34 86 99 21 3,然后建立二叉查找树,中序遍历输出3 7 21 34 59 60 80 86 87 99,针对有序后的元素,存入一个长度为10的数组中,通过折半查找找到21的下标(下标为2),然后输出2

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

typedef int ElemType;
typedef struct BSTNode
{
	ElemType key;
	struct BSTNode* lchild, * rchild;
}BSTNode,*BiTree;
int Insert(BiTree& tree, ElemType data)
{
	if (tree == NULL)
	{
		tree = (BiTree)malloc(sizeof(BSTNode));
		tree->key = data;
		tree->lchild = NULL;
		tree->rchild = NULL;
		return 1;
	}
	else if (data == tree->key)
	{
		return 0;
	}
	else if (data < tree->key)
	{
		Insert(tree->lchild, data);
	}
	else if (data > tree->key)
	{
		Insert(tree->rchild, data);
	}
}

void create(BiTree&tree,ElemType data[],int n)
{
	int i=0;
	while (i<n)
	{
		Insert(tree,data[i]);//插入二叉排序树
		i++;
	}
}
int n = 0;
void InOrder(BiTree tree,ElemType i[])
{
	
	if (tree!=NULL)
	{
		InOrder(tree->lchild,i);
		printf("%3d", tree->key);
		i[n++] = tree->key;
		InOrder(tree->rchild,i);
	}
}

int Binary_Search(ElemType i[],int n)
{
	int low = 0, high = 9, mid = 0;
		while (low<=high)
		{
			mid = (low + high) / 2;
			if (i[mid]==n)
			{
				return mid;
			}
			else if (i[mid] < n)
			{
				low = mid + 1;
			}
			else
			{
				high = mid - 1;
			}
		}
		return -1;
}
int main()
{
	ElemType data[10];
	BiTree tree = NULL;
	int x=0;
	for (int i = 0; i <10; i++)
	{
		scanf("%d", &x);
		data[i] = x;
	}
	create(tree, data, 10);
	InOrder(tree,data);
	printf("\n");
	int a;
	a=Binary_Search(data,21);
	printf("%d", a);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值