2024年6月2日发(作者:)

实验课题一:将下图中的二叉树用二叉链表表示:

A

B

D

F

1 用三种遍历算法遍历该二叉树,给出对应的输出结果;

2 写一个函数对二叉树搜索,若给出一个结点,根据其是否属于该树,输出true或者false。

3 写函数完成习题4.31(C++版)或4.28(C版教科书)。

#include"stdio.h"

#include"stdlib.h"

typedef char Elementtype;

typedef struct treenode *Tree;

struct treenode

{

Elementtype Element;

Tree Left;

Tree Right;

};

void Pre(Tree t)

{

if(t!=NULL)

{

printf("%c",t->Element);

Pre(t->Left);

Pre(t->Right);

}

}

void Aft(Tree t)

{

if(t!=NULL)

{

Pre(t->Left);

Pre(t->Right);

printf("%c",t->Element);

G

E

H

C

}

void Mid(Tree t)

{

if(t!=NULL)

{

Pre(t->Left);

printf("%c",t->Element);

Pre(t->Right);

}

}

}

Tree creat(Tree t)

{

char c;

t=(Tree)malloc(sizeof(struct treenode));

if((c=getchar())!='#')

{

t->Element=c;

t->Left=Pre();

t->Right=Pre();

}

else

t=NULL;

return t;

}

int countnode(Tree T)

{

if(T==NULL)

return 0;

else

return 1+countnode(T->Left)+countnode(T->Right);

}

int countleaf(Tree T)

{

if(T==NULL)

return 0;

else if(T->Left==NULL&&T->Right==NULL)

return 1;

return countleaf(T->Left)+countleaf(T->Right);

}

int countfull(Tree T)

{

if(T==NULL)

return 0;

else

return!(T->Left==NULL||T->Right==NULL)+countfull(T->Left)+countfull(T->Right);

}

int Find(Tree T,char c;)

{ int find;

if(!find&&T!=NULL)

{

if(T->Element==c)

{

find=1;

}

else

{ Find(T->Left,c);

Find(T->Right,c);

}

}

return find;

}

void main()

{

Tree T;

char c;

T=creat(T);

printf("前序遍历为:n");

Pre(T);

printf("n");

printf("中序遍历为:n");

Mid(T);

printf("n");

printf("后序遍历为:n");

Aft(T);

printf("n");

printf("请输入要检测的字符:");

scanf("%c",&c);

getchar();

if(Find(T,c)==1)

printf(" True该字符在树中!n");

else

printf("False该字符不在树中!n");

printf("树中的节点数为:%dn",ountnode(T));

printf("树中的树叶数为:%dn",ountleaf(T));

printf("树中的满节点数为:%dn",countfull(T));

}