二叉树的非层次遍历
"tree.h"
#include<stdio.h>
#include<stdlib.h>
#define MAX_TREE_SIZE 100
#define OK 1
#define False 0;
#define ERROR -1
#define OVERFLOW -1
typedef int Status;
typedef char TElemType;
typedef int ElemType;
typedef char TElemType;
typedef int ElemType;
typedef struct TreeNode* BinTree;
typedef BinTree Position;//BinTNode
struct TreeNode {//BinTNode
ElemType Data;
BinTree Left;
BinTree Right;
};
typedef struct SqStack
{
TreeNode* data[MAX_TREE_SIZE];
int top;
}SqStack, * Stack;
Status IsEmpty(Stack BT);
void Traversal(BinTree BT);
BinTree CreateBiTree(BinTree* T);
/*遞歸遍歷*/
//借用堆栈
typedef int Status;
typedef int SElemType;
//void PreOrderTraversals(BinTree BT);
//void InOrderTrverses(BinTree BT);
//void PostOrderTraverses(BinTree BT);
void PreOrderTraversals(BinTree BT);
void InOrderTraversals(BinTree BT);
void PostOrderTraversals(BinTree BT);
BinTree Push(SqStack* S, BinTree T);
BinTree Pop(SqStack* S);
Tree.cpp
#include"Tree.h"
/*非遞歸遍歷*/
//借用堆栈,堆栈数组定义为指针数组,里面存放的是指向树的结点的指针
Status IsEmpty(Stack S)
{
if (S->top == -1)
return OK;
else
return False;
}
BinTree getTop(SqStack* S)
{
if (S->top == -1)
{
printf("表是空的\n");
exit(0);
}
return (S->data[S->top]);
}
BinTree Push(SqStack* S, BinTree T)
{/*top=-1为栈低*/
if (S->top == MAX_TREE_SIZE - 1)
{
printf("表已经满了!");
exit(0);
}
S->top++;
S->data[S->top] = T;
}
/*POP*/
BinTree Pop(SqStack* S)
{
if (S->top == -1)
{
printf("表是空的\n");
exit(0);
}
return (S->data[S->top--]);
}
void InOrderTraversals(BinTree BT)
{
BinTree T = BT;
Stack S;/*创建并初始化堆栈*/
while (T || !IsEmpty(S))
{/*一直向左并将沿途结点压入堆栈*/
while (T)
{
Push(S, T);
T = T->Left;
}
if (!IsEmpty(S))
{
T = Pop(S);/*访问结点*/
printf("%d", T->Data);
T = T->Right;//转向右子树
}
}
}
/*先序,后序*/
void PreOrderTraversals(BinTree BT)
{
BinTree T = BT;
Stack S ;/*创建并初始化堆栈*/
while (T || !IsEmpty(S))
{/*一直向左并将沿途结点压入堆栈*/
while (T)
{
printf("%d", T->Data);
Push(S, T);
T = T->Left;
}
if (!IsEmpty(S))//获取栈顶元素,转向其右子树
{
T = Pop(S);/*访问结点*/
T = T->Right;//转向右子树
}
}
}
void PostOrderTraversals(BinTree BT)
{
BinTree Pre, T;//pre用于存放上一个访问过的结点,T用于存放当前的结点
T = BT;//用于将新发现的结点压站
Pre = NULL;
Stack S;
while (T || IsEmpty(S))
{
while (T)
{
Push(S, T);
T = T->Left;
}
//while结束是因为找到了最低左端结点
BinTree top = getTop(S);
if (top->Right == NULL || top->Right == Pre)
{//如果又结点为空,或者右孩子已经被访问过来,就要访问该结点
printf("%d", top->Data);
Pop(S);
Pre = top;
}
else
{
T = top->Right;
}
if (!IsEmpty(S))
{
T = getTop(S);
Pop(S);
if (T->Right ==NULL || T->Right == Pre)
{
printf("%d", T->Data);
Pre = T;
}
else
{
Push(S, T);
T = T->Right;
}
}
}