您现在的位置: 破洛洛 >> 建站学院 >> 网站开发 >> CGI教程 >> 正文

二叉树的集合操作

作者:佚名 来源:CNZZ 更新时间:2007-12-28
分享到
以下程序源代码:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#define NULL 0
#define DataType char
typedef struct BinTreeNode *PBinTreeNode;
typedef PBinTreeNode *PBinTree;

struct BinTreeNode
{ DataType info;
PBinTreeNode llink;
PBinTreeNode rlink;
};
PBinTreeNode Create_BinTree(void);

PBinTree Create_BinTreeRoot(void)
{PBinTree pbtree;
pbtree=(PBinTree)malloc(sizeof(struct BinTreeNode));
if(pbtree==NULL) pbtree=(PBinTree)realloc(pbtree,sizeof(struct BinTreeNode));
*pbtree=Create_BinTree();
return (pbtree);
}

PBinTreeNode Create_BinTreeNode(void)
{PBinTreeNode pbnode;
pbnode=(PBinTreeNode)malloc(sizeof(struct BinTreeNode));
if(pbnode==NULL) pbnode=(PBinTreeNode)realloc(pbnode,sizeof(struct BinTreeNode));
else pbnode->llink=pbnode->rlink=(PBinTreeNode)NULL;
return (pbnode);
}

int isalphabet(char i)
{
if (i >= 'a' && i <='z' || i >= 'A' && i <='Z' || i=='@')
return 1;
else return 0;
}

PBinTreeNode Create_BinTree(void)
{PBinTreeNode pbnode ;
DataType i;
printf("Please input a char:\t");
fflush(stdin);
scanf("%c",&i);
fflush(stdin);
while(!isalphabet(i))
{
printf("Sorry, your input char is not in alphabet, please input again:");
scanf("%c",&i);
fflush(stdin);
}
if(i=='@') pbnode= NULL;
else
{
pbnode = (PBinTreeNode)malloc(sizeof(struct BinTreeNode));
if(pbnode == NULL)
{
printf("Out of space!\n");
return pbnode ;
}
pbnode->info=i;
pbnode->llink=Create_BinTree();
pbnode->rlink=Create_BinTree();
}
return pbnode;
}

void outputTree(PBinTreeNode pbnode,int totalSpace)
{int i;
if(pbnode!=NULL)
{
totalSpace+=5;
outputTree(pbnode->rlink,totalSpace);
for(i=0;i<totalSpace;i++) printf(" ");
printf("%c\n",pbnode->info);
outputTree(pbnode->llink,totalSpace);
}
}

void preOrder(PBinTreeNode pbnode)
{
if(pbnode==NULL) return ;
printf("%c\t",pbnode->info);
preOrder(pbnode->llink);
preOrder(pbnode->rlink);
}

void inOrder(PBinTreeNode pbnode)
{
if(pbnode== NULL) return;
inOrder(pbnode->llink);
printf("%c\t",pbnode->info);
inOrder(pbnode->rlink);
}

void postOrder(PBinTreeNode pbnode)
{
if(pbnode == NULL) return ;
postOrder(pbnode->llink);
postOrder(pbnode->rlink);
printf("%c\t", pbnode->info);
}
void leaves(PBinTreeNode pbnode)
{
if(pbnode->llink != NULL && pbnode->rlink == NULL)
leaves(pbnode->llink);
if(pbnode->rlink != NULL && pbnode->llink == NULL)
leaves(pbnode->rlink);
if(pbnode->llink != NULL && pbnode->rlink != NULL)
{
leaves(pbnode->llink);
leaves(pbnode->rlink);
}
if(pbnode->llink == NULL && pb

转载请注明:破洛洛(谢谢合作)
网友评论: