二叉树深度优先遍历(非递归)
1. 先序遍历非递归化
- 从根结点开始入栈一个元素
- 不停的执行以下操作:
- 如果栈不空,就出栈一个元素,并对其进行访问,并访问其左右孩子
- 若左右孩子存在,则依次入栈,右孩子先入栈,左孩子后入栈
- 若没有左右孩子则继续出栈一个元素
- 如果进行出栈操作后栈为空,表明遍历结束
typedef struct BTNode
{
int data;
struct BTNode* lChild;
struct BTNode* rChild;
}BTNode;
void preorder(BTNode *bt)
{
if (bt != NULL)
{
BTNode *Stack[maxSize];
int top = -1;
BTNode *p = NULL;
Stack[++top] = bt;
while (top != -1)
{
p = Stack[top--];
Visit(p);
if (p->rChild != NULL)
Stack[++top] = p->rChild;
if (p->lChild != NULL)
Stack[++top] = p->lChild;
}
}
}
2. 后序遍历非递归化
-
先序遍历:先访问根结点,然后先遍历左子树,最后遍历右子树 -
后序遍历:先后序遍历左子树,然后后续遍历右子树,最后访问根结点 -
逆后续遍历序列:先遍历根,再遍历右子树,最后遍历左子树
typedef struct BTNode
{
int data;
struct BTNode* lChild;
struct BTNode* rChild;
}BTNode;
void preorder2(BTNode *bt)
{
if (bt != NULL)
{
BTNode *Stack1[maxSize];
int top1 = -1;
BTNode *Stack2[maxSize];
int top2 = -1;
BTNode *p = NULL;
Stack1[++top1] = bt;
while (top1 != -1)
{
p = Stack1[top1--];
Stack2[++top2] = p;
Visit(p);
if (p->lChild != NULL)
Stack1[++top1] = p->lChild;
if (p->rChild != NULL)
Stack1[++top1] = p->rChild;
}
while (top2 != -1)
{
p = Stack2[top2--];
Visit(p);
}
}
}
3. 中序遍历非递归化
void ino(BTNode *bt)
{
if (bt != NULL)
{
BTNode *Stack[maxSize];
int top = -1;
BTNode *p = NULL;
p = bt;
while (top != -1||p!=NULL)
{
while (p != NULL)
{
Stack[++top] = p;
p = p->lChild;
}
if (top != -1)
{
p = Stack[top--];
Visit(p);
p = p->rChild;
}
}
}
}
|