二叉树先序中序后序遍历以及层序遍历。利用c++中的stack和queue
<span style="font-size:10px;">#include<iostream>
#include<stdlib.h>
#include<stack>
#include<queue>
#include<vector>
#include<algorithm>
using namespace std;
typedef struct binarytree
{
char data;
binarytree *lchild;
binarytree *rchild;
}bitree;
bitree* create()
{
char ch;
bitree *root=(bitree*)malloc(sizeof(bitree));
cin>>ch;
if(ch=='#')
{root=NULL;}
else
{
root->data=ch;
root->lchild=create();
root->rchild=create();
}
return root;
}
/****递归遍历*****/
void preorder(bitree *root)
{
if(root!=NULL)
{
cout<<root->data;
preorder(root->lchild);
preorder(root->rchild);
}
}
void inorder(bitree *root)
{
if(root!=NULL)
{
inorder(root->lchild);
cout<<root->data;
inorder(root->rchild);
}
}
void postorder(bitree *root)
{
if(root!=NULL)
{
postorder(root->lchild);
postorder(root->rchild);
cout<<root->data;
}
}
/******非递归遍历******/
void preorder1(bitree *root)
{
bitree *p=root;
stack<bitree*> s;
while(p||!s.empty())
{
if(p!=NULL)
{
s.push(p);
cout<<p->data;
p=p->lchild;
}
else
{
p=s.top();
s.pop();
p=p->rchild;
}
}
}
void inorder1(bitree *root)
{
bitree *p=root;
stack<bitree*> s;
while(p||!s.empty())
{
if(p!=NULL)
{
s.push(p);
p=p->lchild;
}
else
{
p=s.top();
s.pop();
cout<<p->data;
p=p->rchild;
}
}
}
void postorder1(bitree *root)
{
bitree *p=root;
stack<bitree*> s;
vector<bitree*> v;
vector<bitree*>::iterator iter;
while(p||!s.empty())
{
if(p!=NULL)
{
s.push(p);
v.push_back(p);
p=p->lchild;
}
else
{
p=s.top();
if(p->rchild!=NULL&&find(v.begin(),v.end(),p->rchild)==v.end())//利用容器判断右子树是否遍历过
{
p=p->rchild;
}
else
{
s.pop();
cout<<p->data;
p=NULL;
}
}
}
}
void levelorder(bitree *root)
{
queue<bitree*> q;
bitree *p=root;
if(root!=NULL)
{
q.push(p);
}
while(!q.empty())
{
p=q.front();
cout<<p->data;
q.pop();
if(p->lchild!=NULL)
{
q.push(p->lchild);
}
if(p->rchild!=NULL)
{
q.push(p->rchild);
}
}
}
int main()
{
bitree *root;
root=NULL;
cout<<"enter the preorder elems of tree"<<endl;
root=create();
cout<<endl;
cout<<"preorder of recursion"<<endl;
preorder(root);
cout<<endl;
cout<<"inorder of recursion"<<endl;
inorder(root);
cout<<endl;
cout<<"postorder of recursion"<<endl;
postorder(root);
cout<<endl;
cout<<"preorder of not recursion"<<endl;
preorder1(root);
cout<<endl;
cout<<"inorder of not recursion"<<endl;
inorder1(root);
cout<<endl;
cout<<"postorder of not recursion"<<endl;
postorder1(root);
cout<<endl;
cout<<"levelorder of not recursion"<<endl;
levelorder(root);
return 0;
}</span>