1. 程式人生 > >二叉樹的三種遍歷簡單版

二叉樹的三種遍歷簡單版

putchar 中序遍歷 ret pri pos 後續遍歷 同學 alloc erro

同學突然向我問二叉樹的三種遍歷代碼。數據結構剛剛學了,自己很吃力的敲了出來。

和老師演示的代碼有很大差距。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define Error -1
#define Right 1

struct BiTnode
{
char data;
struct BiTnode *LChild;
struct BiTnode *RChild;

};

BiTnode *Creat_BinaryTree()
{
BiTnode *t;

t=(BiTnode *)malloc(sizeof(BiTnode));

t->data=getchar();

if(t->data==‘1‘)
{
t=NULL;
return t;
}

t->LChild=Creat_BinaryTree();
t->RChild=Creat_BinaryTree();
return t;
}

void Preorder(BiTnode * t)
{
if(t)
{
putchar(t->data);
Preorder(t->LChild);
Preorder(t->RChild);
}
}

void Midorder(BiTnode * t)
{
if(t)
{
Midorder(t->LChild);
putchar(t->data);
Midorder(t->RChild);
}
}

void Posorder(BiTnode * t)
{
if(t)
{
Posorder(t->LChild);
Posorder(t->RChild);
putchar(t->data);
}
}

int main()
{
BiTnode * t;

t=Creat_BinaryTree();

printf("前序遍歷為:");
Preorder(t);
putchar(‘\n‘);
printf("中序遍歷為:");
Midorder(t);
putchar(‘\n‘);
printf("後續遍歷為:");
Posorder(t);
putchar(‘\n‘);
free(t);
return 0;
}

二叉樹的三種遍歷簡單版