二叉排序树的实现和查找

按照给定的关键字集合,建立二叉排序树。在建立的二叉排序树上查找指定的关键字,查找成功,输出找到该关键字比较的次数;查找不成功,输出-1.

输入

关键字个数n; 
关键字集合; 
要查找的关键字;

输出

查找成功输出比较的次数,否则输出-1。

样例输入

12
25 18 46 2 53 39 32 4 74 67 60 11
74

样例输出

4
#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
int flag;
struct btree
{
	int date;
btree *left, *right;
};

void creathead(btree *&root)
{
	root  = new btree;
	cin  >> root->date;
	root->left  = root->right  = NULL;
}

void creatbtree(btree *& root, int insert)
{
	if (root  == NULL)
	{
		root  = new btree;
		root->date  = insert;
		root->left  = root->right  = NULL;
		return;
	}
	if (root->date < insert)
	{
		creatbtree(root->right, insert);
	}
	else if (root->date>insert)
	{
		creatbtree(root->left, insert);
	}
}

void find(btree *root, int tar, int cnt)
{
	if (root  == NULL)
	{
		return;
	}
	if (tar  == root->date)
	{
		cout  << cnt + 1;
		flag  = 1;
		return;
	}
	else if (tar < root->date)
	{
		find(root->left, tar, cnt  + 1);
	}
	else if (tar > root->date)
	{
		find(root->right, tar, cnt  + 1);
	}
}

int main()
{
	int n;
	cin  >> n;
	btree *root;
	int k;
	flag  = 0;
	int num;
	creathead(root);
	for (int i  = 2; i  <= n; i++)
	{
		cin  >> num;
		creatbtree(root, num);
	}

	cin  >> k;
	find(root, k, 0);
	if (!flag)
		cout  << "-1";
	return 0;
}

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/qq_38271800/article/details/79994984
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞