二叉树的遍历
0. 基础数据结构
0.1 栈
typedef struct SNode{
PBTNode pbtnode;
}SNode;
typedef struct StaticStack{
int top;
int bottom;
SNode Node[MAXLEN];
}SStack;
0.2 队列
typedef struct SNode{
PBTNode pbtnode;
}SNode;
typedef struct CircleQueue{
int front;
int tail;
SNode Node[MAXLEN];
}CQueue;
1. 深度优先遍历
1.1 先序遍历
前序遍历递归
void PreOrder(PBTNode pRoot)
{
if (pRoot != NULL)
{
printf("%c ", pRoot->_data);
PreOrder(pRoot->_pLeft);
PreOrder(pRoot->_pRight);
}
}
前序遍历非递归
void PreOrderNor(PBTNode pRoot)
{
SStack stack;
SNode node;
node.pbtnode = pRoot;
StaticStackInit(&stack); //栈初始化
StackPush(&stack,node); //进栈
while(!CheckStackIsEmpty(stack)) //判断栈是否为空
{
pRoot = GetStackTop(stack).pbtnode; //获取最后一个进栈的元素
printf("%c ", pRoot->_data);
StackPop(&stack); //出栈
if (pRoot->_pRight != NULL)
{
node.pbtnode = pRoot->_pRight;
StackPush(&stack,node);
}
if (pRoot->_pLeft != NULL)
{
node.pbtnode = pRoot->_pLeft;
StackPush(&stack,node);
}
}
}
1.2 中序遍历
中序遍历递归
void InOrder(PBTNode pRoot)
{
if (pRoot != NULL)
{
InOrder(pRoot->_pLeft);
printf("%c ", pRoot->_data);
InOrder(pRoot->_pRight);
}
}
中序遍历非递归
void InOrderNor(PBTNode pRoot)
{
SStack stack;
SNode node;
node.pbtnode = pRoot;
StaticStackInit(&stack);
StackPush(&stack,node);
pRoot = pRoot->_pLeft;
while(!CheckStackIsEmpty(stack))
{
while(pRoot != NULL)
{
node.pbtnode = pRoot;
StackPush(&stack,node);
pRoot = pRoot->_pLeft;
}
pRoot = GetStackTop(stack).pbtnode;
printf("%c ", pRoot->_data);
StackPop(&stack);
pRoot = pRoot->_pRight;
if (pRoot != NULL)
{
node.pbtnode = pRoot;
StackPush(&stack,node);
pRoot = pRoot->_pLeft;
}
}
}
1.3 后序遍历
后序遍历递归
void PostOrder(PBTNode pRoot)
{
if (pRoot != NULL)
{
PostOrder(pRoot->_pLeft);
PostOrder(pRoot->_pRight);
printf("%c ", pRoot->_data);
}
}
后序遍历非递归
void PostOrderNor(PBTNode pRoot)
{
SStack stack;
SNode node;
int flag[100]; //用来标记结点的右子树是否被访问过
int i = 0;
node.pbtnode = pRoot;
StaticStackInit(&stack);
StackPush(&stack,node);
pRoot = pRoot->_pLeft;
while(!CheckStackIsEmpty(stack))
{
while(pRoot != NULL)
{
node.pbtnode = pRoot;
StackPush(&stack, node);
i++;
pRoot = pRoot->_pLeft;
}
pRoot = GetStackTop(stack).pbtnode;
if (pRoot->_pRight != NULL && flag[i] != 1)
{
pRoot = pRoot->_pRight;
node.pbtnode = pRoot;
StackPush(&stack, node);
flag[i] = 1;
i++;
pRoot = pRoot->_pLeft;
}
else
{
printf("%c ", pRoot->_data);
StackPop(&stack);
pRoot = NULL;
i--;
}
}
}
2. 广度优先遍历
void LevelOrder(PBTNode pRoot) // 层序遍历(广度优先遍历)
{
CQueue queue;
SNode node;
CircleQueueInit(&queue); //队列的初始化
node.pbtnode = pRoot;
QueuePush(&queue,node); //进队列
while(!CheckQueueIsEmpty(queue)) //判断队列是否为空
{
if (pRoot->_pLeft != NULL)
{
node.pbtnode = pRoot->_pLeft;
QueuePush(&queue,node);
}
if (pRoot->_pRight != NULL)
{
node.pbtnode = pRoot->_pRight;
QueuePush(&queue, node);
}
printf("%c ", GetQueueTail(queue).pbtnode->_data);
QueuePop(&queue); //出队列
if (!CheckQueueIsEmpty(queue))
pRoot = GetQueueTail(queue).pbtnode; //获取最先进队列的元素
}
}