后序遍历的非递归算法

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

后序遍历非递归算法

typedef enum{L,R} tagtype;

typedef struct

{

Bitree ptr;

tagtype tag;

}stacknode;

typedef struct

{

stacknode Elem[maxsize];

int top;

}SqStack;

void PostOrderUnrec(Bitree t)

{

SqStack s;

stacknode x;

StackInit(s);

p=t;

do

{

while (p!=null) //遍历左子树

{

x.ptr = p;

x.tag = L; //标记为左子树

push(s,x);

p=p->lchild;

}

while (!StackEmpty(s) && s.Elem[s.top].tag==R)

{

x = pop(s);

p = x.ptr;

visite(p->data); //tag为R,表示右子树访问完毕,故访问根结点}

if (!StackEmpty(s))

{

s.Elem[s.top].tag =R; //遍历右子树

p=s.Elem[s.top].ptr->rchild;

}

}while (!StackEmpty(s));

}//PostOrderUnrec

后序算法之二

void BT_PostOrderNoRec(pTreeT root)

{

stack s;

pTreeT pre=NULL;

while ((NULL != root) || !s.empty())

{

if (NULL != root)

{

s.push(root);

root = root->left;

}

else

{

root = s.top();

if (root->right!=NULL && pre!=root->right)

{

root=root->right;

}

else

{

root=pre=s.top();

visit(root);

s.pop();

root=NULL;

}

}

}

}

一个比较容易理解的后序遍历:

void PostOrder(Bitree *t)

{

TreeNode *node = NULL,*last = NULL;

Stack s;

s,Init();

s.push(t);

while(!s.IsEmpty())

{

node = s.pop();

if(last == node->left || last == node->right)//左右子树已经访问完了,该访问根节点了

{

visit(node);

last = node;

}

else if(node->left || node->right) //左右子树未访问,当前节点入栈,左右节点入栈

{

s.push(node);

if(node->right)

s.push(node->right);

if(node->left)

s.push(node->left);

}

else //当前节点为叶节点,访问

{

visit(node);

last = node;

}

}

}

相关文档
最新文档