二叉树的中序非递归遍历
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<stack>
#define ElemType int
#define maxsize 100
using namespace std;
typedef struct BiNode{
ElemType data;
struct BiNode* lchild;
struct BiNode* rchild;
}BiNode,*BiTree;
int num=0;
ElemType arr[19]={1,2,4,8,0,0,9,0,0,5,0,0,3,6,0,0,7,0,0};
//----------------二叉树的建立--------------------
BiTree Creat()
{
ElemType x;
BiTree bt;
x=*(arr+num);
num++;
if(x==0)
bt=NULL;
else if(x>0)
{
bt=(BiNode*)malloc(sizeof(BiNode));
bt->data=x;
bt->lchild=Creat();
bt->rchild=Creat();
}
else
printf("输入错误\n");
return bt;
}
//----------------中序非递归遍历二叉树---------------
void InOrderwithoutRecursion(BiTree bt)
{
if(bt==NULL) //空树返回
{
printf("空树!\n");
return ;
}
stack<BiNode*> s;
//树非空
BiTree p=bt;
BiNode* q;
while(p!=NULL||!s.empty())
{
if(p)
{
s.push(p);
//GetStack(s);
p=p->lchild;
}
else
{
// printf("else ");
q=s.top();
printf("%d ",q->data);
s.pop();
p=q->rchild;
}
} //while
}
//----------------中序递归遍历二叉树-----------------
void InOrderTraverse(BiTree bt)
{
if(bt)
{
InOrderTraverse(bt->lchild);
printf("%d ",bt->data);
InOrderTraverse(bt->rchild);
}
}
//-----------------中序非递归遍历二叉树-----------------
int main()
{
BiTree bt=Creat();
printf("这是递归遍历!\n");
InOrderTraverse(bt);
printf("\n这是非递归遍历!\n");
InOrderwithoutRecursion(bt);
}