数据结构实验7
题目:假设二叉树采用链接存储方式存储,分别编写一个二叉树先序遍历的递归算法和非递归算法。
test.h
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define MAX 128
typedef struct biTreeNode
{
char data;
struct biTreeNode *lchild,*rchild,*parent;
}biTreeNode, *bi;
bi s[MAX];
char node[]={'a','b','d','h','#','#','I','#','#','E','#','#','c','f','#','#','g','j','#','#','k','#','#'};
//char node[]={'A','B','#','D','#','#','C','#','#'};
//建树
biTreeNode *creatBiTree(biTreeNode *T)
{
char ch;
static int i=0;
ch=node[i];
i++;
if(ch=='#')
{
T=NULL;
}
else
{
T=(biTreeNode *)malloc(sizeof(biTreeNode));
if(!T)
exit(0);
T->data=ch;
T->lchild=creatBiTree(T->lchild);
T->rchild=creatBiTree(T->rchild);
}
return T;
}
//递归遍历
void preOrder(biTreeNode *T)
{
if(T==NULL)
return;
else
{
printf("%c ",T->data);
preOrder(T->lchild);
preOrder(T->rchild);
}
}
void nPreOrder(struct biTreeNode *bt)
{
int top=-1; //采用顺序栈,并假定不会发生上溢
while(bt!=NULL || top!=-1) //两个条件都不成立才退出循环
{
while(bt!=NULL)
{
printf("%c ",bt->data);
s[++top]=bt; //将根指针 bt 入栈
bt=bt->lchild;
}
if(top!=-1) //栈非空
{
bt=s[top--];
bt=bt->rchild;
}
}
}
test.c
#include"test.h" int main() { biTreeNode *T; T = creatBiTree(T); printf("递归:\n"); preOrder(T); printf("\n非递归:\n"); nPreOrder(T); return 0; }