数据结构 c代码5:树的三种遍历

下面是用c语言实现的关于树的三种基本遍历:

#include<iostream>
using namespace std;
#include <stack>
#define MAXSIZE 1000
typedef int ElemType;

typedef struct TNode
{
	ElemType data;
	struct TNode *lchild, *rchild;
}TNode, *Tree;

/*建立一颗二叉树*/
void BuildTree(Tree &root, int &index)
{	
	index++;
	ElemType temp[] = {2,4,5,-1,3,-1,-1,-1,0,7,6,-1,-1,-1,8,-1,-1};
	if(temp[index]==-1)
	{
		root = NULL;
		return;
	}
	else
	{
		root = (TNode *)malloc(sizeof(TNode));
		root->data = temp[index];
		BuildTree(root->lchild, index);
		BuildTree(root->rchild, index);
	}
}

/*递归先序遍历*/ 
void preOrder(Tree tree)
{
	if(tree == NULL)
	{
		return;
	}
	else
	{
		printf("%d ", tree->data);
		preOrder(tree->lchild);
		preOrder(tree->rchild); 
	}
}

/*递归中序遍历*/ 
void inOrder(Tree tree)
{
	if(tree == NULL)
	{
		return;
	}
	else 
	{
		inOrder(tree->lchild);
		printf("%d ", tree->data);
		inOrder(tree->rchild);
	}
}
/*递归后序遍历*/ 
void postOrder(Tree tree)
{
	if(tree == NULL)
	{
		return ;
	}
	else
	{
		postOrder(tree->lchild);
		postOrder(tree->rchild);
		printf("%d ", tree->data);
	}
}

/*非递归的进行先序遍历*/
void recurrence_preOrder(Tree tree)
{
	stack<Tree> s;
	Tree p =tree;
	while(p||(!s.empty())) 
	{
		if(p)
		{
			cout<<p->data<<" ";
			s.push(p);
			p=p->lchild;
		}
		else
		{
			p=s.top()->rchild;
			s.pop();			
		}
	}
} 

void recurrence_InOrder(Tree tree)
{
	stack<Tree> s;
	TNode *p = tree;
	while(p||!s.empty())
	{
		while(p)
		{
			s.push(p);
			p = p->lchild;
		}
		if(!s.empty())
		{
			p = s.top();
			cout<<p->data<<" ";
			s.pop();
			p = p->rchild;
		}
	} 
	cout<<endl;
} 
int main()
{
	Tree tree;
	int index = -1;
	BuildTree(tree, index);
	 cout<<"构建的树:"<<endl
	    <<"1            2 "<<endl
	    <<"2        4       0 "<<endl
	    <<"3     5   -1    7  8 "<<endl
	    <<"4  -1  3      6 -1 -1 -1 "<<endl
	    <<"5    -1 -1  -1 -1 "<<endl<<endl;
		
	/*先序遍历*/
	cout<<"递归先序遍历结果为:"<<endl;
	preOrder(tree); 
	
	/*中序遍历*/
	cout<<"\n递归中序遍历结果为:"<<endl; 
	inOrder(tree);
	
	/*后续遍历*/
	cout<<"\n递归后续遍历结果为:"<<endl;
	postOrder(tree);
	
	/*非递归先序遍历*/ 
	cout<<"\n非递归先序遍历的结果为:"<<endl; 
	recurrence_preOrder(tree);
	
	/*非递归中序遍历*/
	cout<<"\n非递归中序遍历的结果为:"<<endl;
	recurrence_InOrder(tree); 
	system("pause");
	return 0;
}

其中由于非递归后续遍历比较麻烦,所以这里没有编写代码。
有不懂的可以留言,如果这篇文章对你有帮助,请帮忙给个赞!!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值