下面是用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;
}
其中由于非递归后续遍历比较麻烦,所以这里没有编写代码。
有不懂的可以留言,如果这篇文章对你有帮助,请帮忙给个赞!!!!