长期以来,很多同学对数的遍历都有一定的恐惧,其实多练练,多研究,发现是不难的,现在我来把数的构建,递归遍历和非递归遍历为大家整理一下,所有的代码均为我自己敲出来的,并且经过了测试,希望给大家一个参考,若有不足之处,欢迎指出交流。
首先我把数存在数组中,字子树为空,则用‘#’代替,根据这个数组创建二叉树的,然后分别进行前序,中序,后序的递归操作和非递归操作,外加层序遍历代码如下:
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100
typedef char ElemType;
typedef struct Node{
ElemType data;
struct Node *lchild,*rchild;
} BiTree,*LBiTree;
//创建二叉树
LBiTree createTree(char *in, int n ,LBiTree T){
LBiTree p = (LBiTree)malloc(sizeof(BiTree));
p->lchild = p->rchild = NULL;
p ->data = in[0];
T = p;
LBiTree queue[MaxSize];
int front=0,rear=0;
queue[rear++] = p;
int c = 1;
while( c < n){
p = queue[front++];
if(in[c]!='#'){
LBiTree q = (LBiTree)malloc(sizeof(BiTree));
q->lchild = q->rchild = NULL;
q ->data = in[c];
p->lchild= q;
queue[rear++] = q;
}
c++;
if(in[c]!='#'){
LBiTree q = (LBiTree)malloc(sizeof(BiTree));
q->lchild = q->rchild = NULL;
q ->data = in[c];
p->rchild= q;
queue[rear++] = q;
}
c++;
}
return T;
}
//前序非递归
bool preOrder(LBiTree T){
printf("Pre order for tree:");
LBiTree p = T;
LBiTree stack[MaxSize];
int top =0, base =0;
while( p!=NULL || top!=base ){
if(p!=NULL){
printf("%c ",p->data);
stack[top++] = p;
p = p->lchild;
} else{
p = stack[--top];
p = p->rchild;
}
}
printf("\n");
return true;
}
//中序序非递归
bool inOrder(LBiTree T){
printf("In order for tree:");
LBiTree p = T;
LBiTree stack[MaxSize];
int top =0, base =0;
while( p!=NULL || top!=base ){
if(p!=NULL){
stack[top++] = p;
p = p->lchild;
} else{
p = stack[--top];
printf("%c ",p->data);
p = p->rchild;
}
}
printf("\n");
return true;
}
//后序非递归
bool postOrder(LBiTree T){
printf("Post order for tree:");
LBiTree p = T,r=NULL;
LBiTree stack[MaxSize];
int top =0, base =0;
while( p!=NULL || top!=base ){
if(p!=NULL){
stack[top++] = p;
p = p->lchild;
} else{
p = stack[top-1];
if(p->rchild != NULL && p->rchild != r ){
p = p->rchild;
stack[top++] = p;
p = p->lchild;
}else{
p = stack[--top];
printf("%c ",p->data);
r = p;
p = NULL;
}
}
}
printf("\n");
return true;
}
//前序递归
void preOrderByRecursion(LBiTree T){
if(T!=NULL){
printf("%c ",T->data);
preOrderByRecursion(T->lchild);
preOrderByRecursion(T->rchild);
}
}
//中序递归
void inOrderByRecursion(LBiTree T){
if(T!=NULL){
inOrderByRecursion(T->lchild);
printf("%c ",T->data);
inOrderByRecursion(T->rchild);
}
}
//后序递归
void postOrderByRecursion(LBiTree T){
if(T!=NULL){
postOrderByRecursion(T->lchild);
postOrderByRecursion(T->rchild);
printf("%c ",T->data);
}
}
//层序
bool levelOrder(LBiTree T){
printf("Level order for tree:");
LBiTree queue[MaxSize];
int front=0,rear=0;
LBiTree p = T;
if(T!=NULL){
queue[rear++] = p;
}
while(front!=rear){
p = queue[front++];
printf("%c ",p->data);
if(p->lchild!=NULL)
queue[rear++]= p->lchild;
if(p->rchild!=NULL)
queue[rear++]= p->rchild;
}
return true;
}