- 6
- 0
- 约3.84千字
- 约 6页
- 2018-04-14 发布于浙江
- 举报
[2018年最新整理]先序遍历的非递归算法
数据结构
1、先序遍历的非递归算法。用c语言写。
void PreOrderUnrec(Bitree t)
{
SqStack s;
StackInit(s);
p=t;
while (p!=null || !StackEmpty(s))
{
while (p!=null) //遍历左子树
{
visite(p-data);
push(s,p);
p=p-lchild;
}//endwhile
if (!StackEmpty(s)) //通过下一次循环中的内嵌while实现右子树遍历
{
p=pop(s);
p=p-rchild;
}//endif
}//endwhile
}//PreOrderUnrec
/////////////////////////////////
#include stdio.h
#include stdlib.h
#include string.h
#define null 0
struct node
{
char data;
struct node *lchild;
struct node *rchild;
};
//先序,中序 建树
struct node *create(char *pre,char *ord,int n)
{
struct node * head;
int ordsit;
head=null;
if(n=0)
{
return null;
}
else
{
head=(struct node *)malloc(sizeof(struct node));
head-data=*pre;
head-lchild=head-rchild=null;
ordsit=0;
while(ord[ordsit]!=*pre)
{
ordsit++;
}
head-lchild=create(pre+1,ord,ordsit);
head-rchild=create (pre+ordsit+1,ord+ordsit+1,n-ordsit-1);
return head;
}
}
//中序递归遍历
void inorder(struct node *head)
{
if(!head)
return;
else
{
inorder(head-lchild );
printf(%c,head-data );
inorder(head-rchild );
}
}
//中序非递归遍历
void inorder1(struct node *head)
{
struct node *p;
struct node *stack[20];
int top=0;
p=head;
while(p||top!=0)
{
while (p)
{
stack[top++]=p;
p=p-lchild ;
}
p=stack[--top];
printf(%c ,p-data );
p=p-rchild ;
}
}
///////////////////////////////////////////////////////////////////////////////////////
二叉树前序、中序、后序三种遍历的非递归算法
1.先序遍历非递归算法void PreOrderUnrec(Bitree *t){ Stack s; StackInit(s); Bitree *p=t; while (p!=NULL || !StackEmpty(s)) { while (p!=NULL) //遍历左子树 { visite(p-data); push(s,p); p=p-lchild; } if (!StackEmpty(s)) //通过下一次循环中的内嵌while实现右子树遍历 { p=pop(s); p=p-rchild; }//endif }//endwhile }2.中序遍历非递归算法void InOrderUnrec(Bitree *t){ Stack s; StackInit(s); Bitree *p=t; while (p
原创力文档

文档评论(0)