//编译环境 visual studio 2008,win32 console application.
//BiTree.c
//二叉树及其递归和非递归遍历
#include <stdlib.h>
#include <stdio.h>
#define MAXKEY 100
#define OK 1
typedef char elemType;
typedef struct _node
{
elemType key;
struct _node *lchild;
struct _node *rchild;
}Node;//二叉树节点
//递归先序遍历
void PreOrder_R(Node *tree)
{
if(tree!=NULL)
{
printf(" %c",tree->key);
PreOrder_R(tree->lchild);
PreOrder_R(tree->rchild);
}
}
//递归中序遍历
void InOrder_R(Node *tree)
{
if(tree!=NULL)
{
InOrder_R(tree->lchild);
printf(" %c",tree->key);
InOrder_R(tree->rchild);
}
}
//递归后序遍历
void PostOrder_R(Node *tree)
{
if(tree!=NULL)
{
PostOrder_R(tree->lchild);
PostOrder_R(tree->rchild);
printf(" %c",tree->key);
}
}
//非递归先序遍历
void PreOrder_NR(Node *tree)
{
Node *stack[100];
int top=0;
Node *p=tree;
while(p!=NULL||top>0)
{
while(p!=NULL)
{
printf(" %c",p->key);
stack[top++]=p;//根节点入栈
p=p->lchild;
}
p=stack[--top];
p=p->rchild;
}
}
//非递归中序遍历
void InOrder_NR(Node *tree)
{
Node *stack[100];
int top=0;
Node *p=tree;
while(p!=NULL||top>0)
{
while(p!=NULL)
{
stack[top++]=p;
p=p->lchild;
}//左孩子入栈
p=stack[--top];
printf(" %c",p->key);
p=p->rchild;
}
}
//非递归后序遍历
void PostOrder_NR(Node *tree)
{
Node *stack[100];
int top=0;
Node *p=tree;
Node *lastvisit=NULL;
while(p!=NULL||top>0)
{
while(p!=NULL)
{
stack[top++]=p;
p=p->lchild;
}//左孩子入栈
p=stack[top-1];
if(p->rchild==NULL||p->rchild==lastvisit)
{
printf(" %c",p->key);
--top;
lastvisit=p;
p=NULL;
}//访问中间节点
else
p=p->rchild;
}
}
//清空树
int DeleteTree(Node *tree)
{
if(tree!=NULL)
{
DeleteTree(tree->lchild);
DeleteTree(tree->rchild);
free(tree);
}
return OK;
}
main()
{
//创建一个二叉树
Node *tree,*p;
p=malloc(sizeof(Node));
p->key='A';
tree=p;
p=malloc(sizeof(Node));
p->key='B';
tree->lchild=p;
p=malloc(sizeof(Node));
p->key='C';
p->lchild=NULL;
p->rchild=NULL;
tree->lchild->lchild=p;
p=malloc(sizeof(Node));
p->key='D';
p->lchild=NULL;
p->rchild=NULL;
tree->lchild->rchild=p;
p=malloc(sizeof(Node));
p->key='E';
p->lchild=NULL;
tree->rchild=p;
p=malloc(sizeof(Node));
p->key='F';
p->lchild=NULL;
p->rchild=NULL;
tree->rchild->rchild=p;
printf("递归先序遍历:\n");
PreOrder_R(tree);
printf("\n非递归先序遍历:\n");
PreOrder_NR(tree);
printf("\n递归中序遍历:\n");
InOrder_R(tree);
printf("\n非递归中序遍历:\n");
InOrder_NR(tree);
printf("\n递归后序遍历:\n");
PostOrder_R(tree);
printf("\n非递归后序遍历:\n");
PostOrder_NR(tree);
printf("\n");
DeleteTree(tree);
}
数据结构的C实现_二叉树
最新推荐文章于 2021-11-27 22:38:48 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)