6-12 二叉树的遍历(非递归)
要求使用非递归的方式实现中序遍历,并输出中序序列
函数接口定义:
在这里描述函数接口。例如:
void Inorder(BinTree BT) /*中序遍历的非递归算法 */
其中 BinTree
的结构定义为:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
堆栈
的结构定义为:
/*定义堆栈*/
typedef struct SNode *PtrToSNode;
struct SNode{
int top;
BinTree Data[MAXSIZE];
};
typedef PtrToSNode Stack;
/*初始化堆栈*/
Stack CreateStack()
{
Stack S = (Stack)malloc(sizeof(struct SNode));
S->top = -1;
return S;
}
裁判测试程序样例:
在这里给出函数被调用进行测试的例子。例如:
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef struct TNode * BinTree; /* 二叉树类型 */
typedef char ElementType;
struct TNode{ /* 树结点定义 */
ElementType Data; /* 结点数据 */
BinTree Left; /* 指向左子树 */
BinTree Right; /* 指向右子树 */
};
/*定义堆栈*/
typedef struct SNode *PtrToSNode;
struct SNode{
int top;
BinTree Data[MAXSIZE];
};
typedef PtrToSNode Stack;
/*初始化堆栈*/
Stack CreateStack()
{
Stack S = (Stack)malloc(sizeof(struct SNode));
S->top = -1;
return S;
}
void Inorder(BinTree BT); /*中序遍历的非递归算法 */
//按先序次序输入二叉树中结点的值(一个字符),@表示空树,构造二叉链表表示二叉树T
BinTree CreatBinTree()
{
ElementType ch;
BinTree T;
scanf("%c",&ch); /*按先序次序输入树的结点,空树输入@*/
if(ch == '@')
T = NULL;
else {
T = (BinTree)malloc(sizeof(struct TNode));
T->Data = ch;
T->Left = CreatBinTree();
T->Right = CreatBinTree();
}
return T;
}
/* 请在这里填写答案 */
int main()
{
BinTree BT;
BT = CreatBinTree();
if(BT == NULL){
printf("\n空树!\n");
}else{
printf("中序遍历的结果为(非递归):");
Inorder(BT);
}
return 0;
}
输入样例:
在这里给出一组输入。例如:
ABC@@DE@G@@F@@@
输出样例:
在这里给出相应的输出。例如:
中序遍历的结果为(非递归):CBEGDFA
代码如下:
Stack StackEmpty(Stack S)//判栈空
{
if(S->top==-1)
return 1;
else return 0;
}
Stack Push(Stack S,BinTree BT)//进栈
{
if(S->top==MAXSIZE-1)
return 0;
S->top=S->top+1;
S->Data[S->top]=BT;
}
BinTree Pop(Stack S,BinTree BT)//出栈
{
if(S->top==-1)
return 0;
BT=S->Data[S->top];
S->top--;
return BT;
}
void Inorder(BinTree BT)//中序遍历(非递归)
{
Stack S=(Stack)malloc(sizeof(struct SNode));
S=CreateStack();/*初始化堆栈*/
BinTree p=BT;//p是遍历指针
while(p||!StackEmpty(S))//栈不空或者p不空循环
{
while(p!=NULL){ //根指针进栈,遍历左子树
Push(S,p); //每遇到非空二叉树先向左走
p=p->Left;
}
if(p==NULL){ //根指针退栈,访问根结点,遍历右子树
p=Pop(S,p); //退栈
putchar(p->Data);// printf("%c",p->Data);访问根结点
p=p->Right; //再向右子树走
}
}
}