字符串二叉树的实现

来源:互联网 发布:python 输入ctrl c 编辑:程序博客网 时间:2024/05/01 14:54
//binTree.h#ifndef BINTREE_H#define BINTREE_H#include <stdio.h>#include <malloc.h>#include <string.h>//二叉树结构体typedef struct node{    char data[15];    struct node * lchild;    struct node * rchild;}node;node * Insert(node *t , char *key);int TreeDepth(node *t);void InOrder(node * t);int leaves(node *t);int countStr(node *t);#endif//main.c#include <stdio.h>#include "binTree.h"int main(int argc, char **argv){    int Depth = 0, leaveNum = 0, leftDepth = 0, rightDepth = 0, allStr = 0,leftStr = 0, rightStr = 0;    node * t = NULL;    char buf[15];    FILE *fp1, *fp2;    fp1 = fopen(argv[1], "r");    fp2 = fopen(argv[2], "w");    if(fp1 == NULL){        printf("read file error!\n");        return -1;    }    while(fgets(buf,15,fp1)!=NULL){       //printf("%s",buf);       t=Insert(t,buf);     }    //t = create(t);    //InOrder(t);    Depth = TreeDepth(t);    leaveNum = leaves(t);    leftDepth = TreeDepth(t->lchild);    rightDepth = TreeDepth(t->rchild);    allStr = countStr(t);    leftStr = countStr(t->lchild);    rightStr = countStr(t->rchild);    fprintf(fp2, "No. of strings in the input file=%d\n", allStr);    fprintf(fp2, "Height of the search tree=%d\n", Depth);    fprintf(fp2, "Number of leaves in the tree=%d\n", leaveNum);    fprintf(fp2, "Height of the left subtree of root=%d\n",leftDepth);    fprintf(fp2, "No. of strings in the left subtree=%d\n", leftStr);    fprintf(fp2, "Height of the right subtree of root=%d\n",rightDepth);    fprintf(fp2, "No. of strings in the right subtree=%d\n", rightStr);    return 0;}//handle.c#include "binTree.h"//计算树的深度int TreeDepth(node *t){    int rightdep=0;    int leftdep=0;    if(t==NULL)        return -1;    if(t->lchild!=NULL)        leftdep=TreeDepth(t->lchild);    else        leftdep=-1;     if(t->rchild!=NULL)        rightdep=TreeDepth(t->rchild);    else        rightdep=-1;    return (rightdep>leftdep)?rightdep+1:leftdep+1;}//中序遍历void InOrder(node * t)        {    if(t != NULL)    {        InOrder(t->lchild);        printf("%s ", t->data);        InOrder(t->rchild);    }}//计算树的叶子数int leaves(node *t){    int leavesNum = 0;    if(t != NULL)    {        if(t->lchild==NULL&&t->rchild==NULL)            return 1;        leavesNum+=leaves(t->lchild);        leavesNum+=leaves(t->rchild);    }    return leavesNum;}//计算节点数目int countStr(node *t){    int count = 0;    if(t != NULL){        count = 1;        count+=countStr(t->lchild);        count+=countStr(t->rchild);    }    return count;}//makefileobjects = binTree.o handle.o main.orun : $(objects)    cc -o run $(objects)main.o : binTree.h handle.o : binTree.hbinTree.o : binTree.h.PHONY : cleanclean :    rm run $(objects)
0 0