- 2.4 用
递归法(非递归法)实现先序遍历、中序遍历和后序遍历函数,要求遍历时能执行一定的操作,且该操作可由遍历函数的调用者来设置。
提示:可将结点定义成如下结构体:
#define TREE_TYPE int
typedef struct TREE_NODE{
TREE_TYPE value;
struct TREE_NODE *left;
左结点指针
struct TREE_NODE *right;
右结点指针
}TreeNode;
先序遍历与创建二叉树;递归法
#include "tree.h"
#include <stdio.h>
btree *creat_bintree(btree *t)
{ char ch;
printf("/n enter ch in preorder, 1 for no child:");
ch=getchar();
getchar();
if ( ch=='1')
{
printf("The tree has only head node!/n");
t = NULL;
}
else
{
t = (btree *)malloc(sizeof(btree));
t->data=ch;
t->lchild = (btree *)creat_bintree( t->lchild );
t->rchild = (btree *)creat_bintree( t->rchild );
}
return(t);
}
非递归实现;
#include "tree.h"
void preorder_norecu(btree *t)
{
btree *s[20], *p =t; //p is the current node
int top = 0;
while(p || top) // p isn't NULL
if(p)
{
visit(p); //visit the cur node
++top;
s[top] = p; //save cur node to s[top];
p=p->lchild; //p is directed to lchild node;
}
else //p is NULL
{
p=s[top]; //let p direct to s[top];
--top; //decrease the top;
p=p->rchild; //test rchild is NULL or not?
}
}
中序遍历;
#include "tree.h"
void in_tree(btree *t)
{
if(t == NULL)
return -1;
else
{
in_tree(t->lchild);
putchar(t->data);
in_tree(t->rchild);
}
}
非递归实现:
#include "tree.h"
void in_norecursive(btree *t)
{
btree * s[MAX],*p=t; //p is directed to head node;
int top=0;
while(p || top !== NULL) //p isn't NULL
if(p)
{
top++; //top add
s[top]=p; //save current node;
p=p->lchild; //let p directed to lchild;
}
else
{
p=s[top]; //p is NULL,let p directed to s[top];
--top; //push(s)
visit(p); //visit the p node;
p=p->rchild; //direct the right child;
}
}
后续遍历同上;