二叉树的创建和各种递归非递归遍历方法研究(一)

先来看看具体代码如下:

// BinTree1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
typedef struct node  
{
	char data;
	struct node* lchild;
	struct node* rchild;
}binTree;

binTree* createBinTree()
{
	
	char x;
	cin>>x;
	binTree* temp;
	if(x=='$')
		temp =NULL;
	else
	{
		temp = new binTree();
		temp->data=x;
		temp->lchild=createBinTree();
		temp->rchild = createBinTree();
	}
	return temp;
}

//按照层次遍历树
void Levelorder(binTree* root)
{
	queue<binTree*> T;
	T.push(root);
	while(!T.empty())
	{
		root =T.front();
		cout<<root->data;
		T.pop();
		if (root->lchild)
		{
			T.push(root->lchild);
		}
		if (root->rchild)
		{
			T.push(root->rchild);
		}
	}
}

//递归先序遍历
void Preorder1(binTree* root)
{
	if (root!=NULL)
	{
		cout<<root->data;
		Preorder1(root->lchild);
		Preorder1(root->rchild);
	}
}
//递归中序遍历
void Midorder1(binTree* root)
{
	if (root!=NULL)
	{
		Midorder1(root->lchild);
		cout<<root->data;
		Midorder1(root->rchild);
	}
}
//递归后序遍历
void Afterorder1(binTree* root)
{
	if (root!=NULL)
	{
		Afterorder1(root->lchild);
		Afterorder1(root->rchild);
		cout<<root->data;
	}
}
//非递归先序遍历
void Preorder2(binTree* root)
{
	stack<binTree*> T;
	while(root!=NULL || !T.empty())
	{
		while (root!=NULL)
		{
			cout<<root->data;
			T.push(root);
			root=root->lchild;
		}
		root=T.top();
		T.pop();
		root=root->rchild;
	}
}


//非递归中序遍历
void Midorder2(binTree* root)
{
	stack<binTree*> T;
	while (root!=NULL || !T.empty())
	{
		
		while (root!=NULL)
		{
			T.push(root);
			root=root->lchild;
		}
		root=T.top();
		T.pop();
		cout<<root->data;
		root=root->rchild;


	}
}
//非递归后序遍历
void Afterorder2(binTree* root)
{
	binTree *pre=NULL;
	stack<binTree*> T;
	while(root!=NULL || !T.empty())
	{
		while(root!=NULL)
		{
			T.push(root);
			root=root->lchild;
		}
		root=T.top();
		if (root->rchild==NULL || root->rchild==pre)
		{
			cout<<root->data;
			T.pop();
			pre=root;
			root=NULL;
		}
		else
		{

			root=root->rchild;
		}
	}

}
int _tmain(int argc, _TCHAR* argv[])
{
	cout<<"请输入元素,$代表null"<<endl;
	binTree* root = createBinTree();
	cout<<"按照层次遍历该树:";
	Levelorder(root);
	cout<<endl;
	cout<<"递归先序遍历:";
	Preorder1(root);
	cout<<endl;
	cout<<"递归中序遍历:";
	Midorder1(root);
	cout<<endl;
	cout<<"递归后序遍历:";
	Afterorder1(root);
	cout<<endl;
	cout<<"非递归先序遍历:";
	Preorder2(root);
	cout<<endl;
	cout<<"非递归中序遍历:";
	Midorder2(root);
	cout<<endl;
	cout<<"非递归后序遍历:";
	Afterorder2(root);
	cout<<endl;
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值