二叉搜索树

/*
2:二叉搜索树
查看 提交 统计 提问
总时间限制: 1000ms 内存限制: 1024kB
描述
   二叉搜索树在动态查表中有特别的用处,一个无序序列可以通过构造一棵二叉搜索树变成一个有序序列,
   构造树的过程即为对无序序列进行排序的过程。每次插入的新的结点都是二叉搜索树上新的叶子结点,
   在进行插入操作时,不必移动其它结点,只需改动某个结点的指针,由空变为非空即可。

   这里,我们想探究二叉树的建立和序列输出。

输入
只有一行,包含若干个数字,中间用空格隔开。(数字可能会有重复)
输出
输出一行,对输入数字建立二叉搜索树后进行前序周游的结果。
样例输入
41 467 334 500 169 724 478 358 962 464 705 145 281 827 961 491 995 942 827 436 
样例输出
41 467 334 169 145 281 358 464 436 500 478 491 724 705 962 827 961 942 995 
*/

#include <iostream>
using namespace std;
struct node
{
	int info;
	node *l, *r;
};
void pre(node *root)
{
	if (root)
	{
		cout << root->info << ' ';
		pre(root->l);
		pre(root->r);
	}
}
int main()
{
	int temp;
	node *root = new node,*cur,*next;
	cin >> temp;
	root->info = temp;
	root->l = NULL;
	root->r = NULL;
	while (cin >> temp)
	{
		next = root;
		cur = new node;
		cur->info = temp;
		cur->l = NULL;
		cur->r = NULL;
		while (next)
		{
			if (temp == next->info)
				break;
			if (temp < next->info)
			{
				if (next->l)
					next = next->l;
				else
				{
					next->l = cur;
					break;
				}
			}
			else
			{
				if (next->r)
					next = next->r;
				else
				{
					next->r = cur;
					break;
				}
			}
		}
	}
	pre(root);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值