关于C++二分搜索树的中序遍历和先序遍历

这里即将介绍如何对一个二分查找树进行中序遍历和先序遍历进行操作

下面是源代码其中包括自己写的一段建树操作的函数

#include<iostream>
using namespace std;
struct Node
{
	Node *lc;
	Node *rc;
	int data;
	Node(int a)
	{
		data = a;
		lc = NULL;
		rc = NULL;
	}
}; 
void built(Node* &root , int a)
{
	if(root == NULL)
	{
		root = new Node(a);
		root->lc = NULL;
		root->rc = NULL;
	}
	else
	{
		if(a > root->data)
		{
			return built(root->rc , a);
		}
		else
		{
			return built(root->lc , a);
		}
	}
}
void inorder(Node* root)
{
	if(root != NULL)//即为先对左子树进行遍历,到底后输入在逐步对右子树进行遍历,也可以验证二分搜索树是否有序
	{
		inorder(root->lc);
		cout << root->data << " ";
		inorder(root->rc);
	}
}
void preorder(Node* root)
{
	if(root != NULL)//先输出根值在对左子树进行遍历,最后对右子树进行遍历
	{
		cout << root->data << " ";
		preorder(root->lc);
		preorder(root->rc);
	}
}
int main()
{
	int n;
	cout << "请输入元素数目:";
	while(cin >> n && n != 0)
	{ 
		Node *root = NULL;
		cout << "请输入元素:";
		for(int i = 0 ; i < n ; i ++)
		{
			int a;
			cin >> a;
			built(root,a);
		}
		cout << "中序遍历结果为:";
		inorder(root);
		cout << endl;
		cout << "前序遍历结果为:";
		preorder(root); 
		cout << endl << "请输入下一次元素数目,结束请输入'0':"; 
	}
	cout << endl;
	return 0;
} 

运行结果如图:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值