#include <stdio.h>
#include <stdlib.h>
#include<bits/stdc++.h>
using namespace std;
typedef struct BiTNode{ //定义二叉树
int data;
bool visitflag; //用于判断是否已经访问过该节点
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
//栈的定义 ****************************************
#define MAXSIZE 50
#define ElemType BiTree
typedef struct { //定义顺序栈
ElemType data[MAXSIZE];
int top;
}SqStack;
void InitStack(SqStack &S)
{
S.top=-1;
}
bool StackEmpty(SqStack S)
{
if(S.top==-1)
return true;
else
return false;
}
bool Push(SqStack &S,ElemType x)
{
if(S.top==MAXSIZE-1)
{
cout<<"栈满!"<<endl;
return false;
}
S.data[++S.top]=x;
return true;
}
bool Pop(SqStack &S,ElemType &x)
{
if(S.top==-1)
{
cout<<"栈空!"<<endl;
return false;
}
x=S.data[S.top--];
return true;
}
bool GetTop(SqStack S,ElemType &x)
{
if(S.top==-1)
{
cout<<"栈空!"<<endl;
return false;
}
x=S.data[S.top];
return true;
}
//************************************************
SqStack S;
//二叉树的定义************************ ******************
void InitNode(BiTree &root,int i) //初始化一个节点
{
root=(BiTree)malloc(sizeof(BiTNode));
root->data=i;
root->visitflag=false;
root->lchild=NULL;
root->rchild=NULL;
}
void InitT(BiTree &root) //初始化一个树
{
root=(BiTree)malloc(sizeof(BiTNode));
root->data=0;
BiTNode *N1; //初始化各个节点
InitNode(N1,1);
BiTNode *N2;
InitNode(N2,2);
BiTNode *N3;
InitNode(N3,3);
BiTNode *N4;
InitNode(N4,4);
BiTNode *N5;
InitNode(N5,5);
//开始建立各个节点的关系
root->lchild=N1;
root->rchild=N2;
N1->lchild=N3;
N1->rchild=N4;
N2->lchild=N5;
}
int visitT(BiTree &root) //访问二叉树
{
cout<<root->data<<" ";
root->visitflag=true;
}
void Preorder(BiTree T) //(递归)先序遍历 根-左-右
{
if(T!=NULL)
{
visitT(T);
Preorder(T->lchild);
Preorder(T->rchild);
}
}
void Inorder(BiTree T) //(递归)中序遍历 左-根-右
{
if(T!=NULL)
{
Inorder(T->lchild);
visitT(T);
Inorder(T->rchild);
}
}
void Postorder(BiTree T) //(递归)后序遍历 左-右-根
{
if(T!=NULL)
{
Postorder(T->lchild);
Postorder(T->rchild);
visitT(T);
}
}
//*******************
void InOrder2(BiTree T) //非递归中序遍历
{
InitStack(S);BiTree p=T;
while(p||!StackEmpty(S))
{
if(p)
{
Push(S,p); //当前节点入栈
if(!p->visitflag) //!!!attention!不能重复访问一个结点否则会陷入死循环 所以设置一个标志位
p=p->lchild; //左孩子不空一直往左走
}
else
{
Pop(S,p);visitT(p); //栈顶元素出栈,访问出栈结点
p=p->rchild;
}
}
}
void PreOrder2(BiTree T) //非递归先序遍历
{
InitStack(S);BiTree p=T;
while(p||!StackEmpty(S))
{
if(p)
{
visitT(p);
Push(S,p); //当前节点入栈
p=p->lchild; //左孩子不空一直往左走
}
else
{
Pop(S,p); //栈顶元素出栈,访问出栈结点
p=p->rchild;
}
}
}
main()
{
BiTree root=NULL; //定义一个节点
InitT(root);
cout<<"先序非递归遍历结果: ";
PreOrder2(root);
cout<<endl;
InitT(root);
cout<<"中序非递归遍历结果: ";
InOrder2(root);
}
数据结构5.4-二叉树非递归的中序先序遍历(利用栈实现)
最新推荐文章于 2022-07-12 23:24:38 发布