先来看看具体代码如下:
// 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;
}