二叉树的三种递归遍历算法

二叉树本身是一种递归的数据类型,二叉树的许多操作离不开递归。

include <stdio.h>

include<stdlib.h>

include<stdbool.h>

typedef int TElemtype;

typedef struct BiTNode
{
TElemtype Data;
int IfVisited;
struct BiTNode* Lchild, * Rchild;

}BiTNode;
typedef BiTNode* BiTree;

void PrintTree(BiTree Tree)
{
printf("%d ", Tree->Data);
}

void PreOrder(BiTree Tree, void(*Visit)(BiTree))
{
if (Tree) {
Visit(Tree);
PreOrder(Tree->Lchild, Visit);
PreOrder(Tree->Rchild, Visit);
}

}

void InOrder(BiTree Tree, void(*Visit)(BiTree))
{
if (Tree)
{
InOrder(Tree->Lchild, Visit);
Visit(Tree);
InOrder(Tree->Rchild, Visit);
}
}

void PostOrder(BiTree Tree, void (*Visit)(BiTree))
{
if (Tree)
{
PostOrder(Tree->Lchild, Visit);
PostOrder(Tree->Rchild, Visit);
Visit(Tree);
}
}

BiTree CreateNode(int item)
{
BiTree t = (BiTree)malloc(sizeof(BiTNode));
t->Data = item;
t->IfVisited = false;
t->Lchild = NULL;
t->Rchild = NULL;
return t;
}

int main()
{
BiTree N[9];

for (int i = 0; i < 9; i++) { N[i] = CreateNode(i); N[i]->IfVisited = 0; }
N[0]->Lchild = N[1]; N[0]->Rchild = N[2];
N[1]->Lchild = N[3];
N[2]->Lchild = N[4]; N[2]->Rchild = N[5];
N[3]->Rchild = N[6];
N[6]->Lchild = N[7]; N[6]->Rchild = N[8];
}

posted @ 2021-04-11 20:41  empty_thought  阅读(390)  评论(0)    收藏  举报