数据结构之二叉树的递归建立,BFS遍历,先序中序后序遍历

#include "iostream"
#include "queue"
using namespace std;
struct Node
{
	int data;
	struct Node *lchild;
	struct Node *rchild;
};
Node* CreateNode();
void BFS(Node *node);//层次遍历,也叫广度优先搜索遍历
void Xianxu(Node *node);//先序遍历
void Zhongxu(Node *node);//中序遍历
void Houxu(Node *node);//后序遍历
int main()
{
	cout << "从键盘输入创建二叉树,输入-1表示该左子树或右子树为空"<<endl;
	Node *node = CreateNode();//从键盘输入创建二叉树,输入-1表示该左子树或右子树为空
	cout << "广度优先搜索的序列是" << endl;
	BFS(node);
	cout << endl;
	cout << "先序序列是" << endl;
	Xianxu(node);
	cout << endl;
	cout << "中序序列是" << endl;
	Zhongxu(node);
	cout << endl;
	cout << "后序序列是" << endl;
	Houxu(node);
	system("pause");
	return 0;
}
//递归建立二叉树
Node* CreateNode()
{
	Node *node=new Node();
	//Node *node
	int d;
	cin >> d;
	if (d == -1)
	{
		node = NULL;
	}
	else
	{
		node->data = d;
		node->lchild = CreateNode();
		node->rchild = CreateNode();

	}
	return node;
}
//广度优先搜索
void BFS(Node *node)
{
	queue<Node *> nodeQueue;
	nodeQueue.push(node);
	while (!nodeQueue.empty())
	{
		Node *tnode;
		tnode = nodeQueue.front();
		nodeQueue.pop();
		cout << tnode->data << " ";
		if(tnode->lchild!=NULL)
		nodeQueue.push(tnode->lchild);
		if (tnode->rchild != NULL)
		nodeQueue.push(tnode->rchild);
	}
}
void Xianxu(Node *node)
{

	if (node != NULL) 
	{
		cout << node->data << " ";
		Xianxu(node->lchild);
		Xianxu(node->rchild);
	}
	
}
void Zhongxu(Node *node)
{
	if (node != NULL)
	{
		Zhongxu(node->lchild);
		cout << node->data << " ";
		Zhongxu(node->rchild);
	}

}
void Houxu(Node *node)
{
	if (node != NULL)
	{
		Houxu(node->lchild);
		Houxu(node->rchild);
		cout << node->data << " ";
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值