递归与非递归
#include <iostream>
#include <stack>
using namespace std;
typedef struct BiNode
{
int num;
struct BiNode *lchild,*rchild;
}BiNode,*BiTree;
int createTree(BiTree &T)//先序构造二叉树
{
int data;
cin>>data;
if(data==0)
{
T=NULL;
}
else
{
T=(BiTree)malloc(sizeof(BiNode));
T->num=data;
createTree(T->lchild);
createTree(T->rchild);
}
return 0;
}
void printTree(BiTree &T)//打印节点
{
if(T!=NULL)
cout<<T->num<<" ";
}
int preOrder(BiTree &T)//递归先序遍历
{
if(T!=NULL)
{
printTree(T);
preOrder(T->lchild);
preOrder(T->rchild);
}
return 0;
}
int inOrder(BiTree &T)//递归中序遍历
{
if(T!=NULL)
{
inOrder(T->lchild);
printTree(T);
inOrder(T->rchild);
}
return 0;
}
int postOrder(BiTree &T)//递归后续遍历
{
if(T!=NULL)
{
postOrder(T->lchild);
postOrder(T->rchild);
printTree(T);
}
return 0;
}
int preOrder2(BiTree &T)//非递归先序
{
stack<BiTree> sta;
BiTree p = T;
while(p||!sta.empty())
{
if(p!=NULL)
{
sta.push(p);
cout<<p->num<<" ";
p=p->lchild;
}
else
{
p = sta.top();
sta.pop();
p = p->rchild;
}
}
return 0;
}
int inOrder2(BiTree &T)//非递归中序
{
stack<BiTree> sta;
BiTree p = T;
while(p||!sta.empty())
{
if(p!=NULL)
{
sta.push(p);
p=p->lchild;
}
else
{
p = sta.top();
cout<<p->num<<" ";
sta.pop();
p = p->rchild;
}
}
return 0;
}
int postOrder2(BiTree T)//非递归后序遍历
{
stack<BiTree> sta;
BiTree p =T, r=NULL,temp;
while(p||!sta.empty())
{
if(p)
{
sta.push(p);
p=p->lchild;
}
else
{
p= sta.top();
if(p->rchild&&p->rchild!=r)
{
p = p->rchild;
sta.push(p);
p=p->lchild;
}
else
{
p=sta.top();
sta.pop();
cout<<p->num<<" ";
r=p;
p=NULL;
}
}
}
return 0;
}
int main()
{
BiTree T;//指针
cout<<"create a tree: ";
createTree(T);
cout<<"recursive preOrder: ";
preOrder(T);
cout<<endl;
cout<<"recursive inOrder: ";
inOrder(T);
cout<<endl;
cout<<"recursive postOrder: ";
postOrder(T);
cout<<endl;
cout<<"non-recursive postOrder2: ";
preOrder2(T);
cout<<endl;
cout<<"non-recursive inOrder2: ";
inOrder2(T);
cout<<endl;
cout<<"non-recursive postOrder2: ";
postOrder2(T);
cout<<endl;
}