首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

问一个关于建立二叉树的有关问题

2012-03-16 
问一个关于建立二叉树的问题程序是挺长的,呵呵!麻烦帮帮忙我想问:假如输入five,six,two三个单词问tree函数

问一个关于建立二叉树的问题
程序是挺长的,呵呵!麻烦帮帮忙   我想问:
假如输入five,six,two三个单词
问tree函数每次返回的P是指向那里的?

define   maxword   20
mian()
{struct   tnode   *root,*tree();
char   *t;
root=null;
    while((t=getword())!=NULL)
      root=tree(root,t);
      treeprint(root);
}

char   *getword()
{char   *p;
    if((p=malloc(maxword+1))==NULL)
        {printf( "out   of   memory\n ");
          return(NULL);}
scanf( "%maxwords ",p);
      if(strlen(p)==0)return(NULL);
          return(p);
}

struct   tnode   *tree(p,w)
struct   tnode   *p;
char   *w;
{struct   tnode   *talloc();
int   cound;
      if(p==NULL)
          {p==talloc();
            p-> word=w;
            p-> count=1;
            p-> left=p-> right=NULL;}
      else   if((cound=strcmp(w,p-> word))==0)
                      p-> count++;
                else   if(cound <0)
                                p-> left=tree(p-> left,w);
                          else
                                p-> right=tree(p-> right,w);
return(p);}

treeprint(p)
struct   tnode   *p;
{if(p!=NULL)
{treeprint(p-> left);
print( "%4d%s\n ",p-> count,p-> word);
treeprint(p-> ringht);}
}  

struct   tnode   *talloc()
{return((struct   tnode   *)malloc(sizeof(struct   tnode)));
}

[解决办法]
楼主也看的吉林大学那个教程吧
这道题我也做了,不过没调通,请前辈帮忙看看。

//生成一棵二叉树,比较单词出现的次数
//c++ java Fortran basic Foxbase
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXWORD 20
struct tnode{
char *word; //指向一个单词
int count; //访问次数
struct tnode *left; //左孩子
struct tnode *right; //右孩子
};
char *GetWord()
{
char *p;
if((p=(char*)malloc(MAXWORD+1))==NULL) {printf( "Out of memory!\n ");return(NULL);}
scanf( "%s ",p);
if(strlen(p)==0) return(NULL);
return p;
}
struct tnode *tree(struct tnode *pp,char *w)
{
struct tnode *talloc();
int cond;
if(pp==NULL)
{
pp=talloc();
pp-> word=w;
pp-> count=1;
pp-> left=pp-> right=NULL;
}
else if((cond=strcmp(w,pp-> word))==0)
pp-> count++;
else if(cond <0)
pp-> left=tree(pp-> left,w);
else
pp-> right=tree(pp-> right,w);
return(pp);
}
void treeprint(struct tnode *point)
{
if(point!=NULL)
{
treeprint(point-> left);
printf( "%4d%s\n ",point-> count,point-> word);
treeprint(point-> right);
}
}
struct tnode *talloc()
{
return((struct tnode*)malloc(sizeof(struct tnode)));


}
int main()
{
struct tnode *root;
char *t;
root=NULL;
while((t=GetWord())!= "EOF ")
root=tree(root,t);
treeprint(root);
return 0;
}

[解决办法]
应指向这个树的根结点
[解决办法]
cound=strcmp(w,p-> word)
左子树,右子树,都是由 cound 决定的,
root-> word=five
root-> right-> word=six(six> five cound> 0)
root-> right-> right-> word=two(two> five cound> 0 在five的右子树中
               two> six cound> 0 )
[解决办法]
为什么不用递归呢

热点排行