注册 登录
编程论坛 数据结构与算法

树的叶子节点和非叶子结点为什么求不出来啊?

cwl168 发布于 2013-01-08 20:48, 729 次点击
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct Node
{
      int data;
      struct Node *lchild;
      struct Node *rchild;
}BiTree,*BiTNode;

BiTNode InitDSTable()
{
    char ch;
    BiTNode t;
    ch=getchar();
    if(ch=='#')
    {  
         return NULL;
    }
    else
    {
      t=(BiTNode)malloc(sizeof(BiTree));  
      t->data=ch;
      t->lchild=InitDSTable();
      t->rchild=InitDSTable();
    }
    return t;
}
//递归中序遍历
void InOrderTravese(BiTNode T)
{
    if(T)
    {
        InOrderTravese(T->lchild);
        printf("%c",T->data);
        InOrderTravese(T->rchild);
    }
}
//求叶子的结点数和非叶子结点数
int  n1=0,n2=0;//n1非叶子结点,n2为叶子结点数
void Count(BiTNode T)
{
     if(T->lchild==NULL && T->rchild==NULL)
              n1++;
          else
              n2++;
     Count(T->lchild);
     Count(T->rchild);

}
int main()
{     
      printf("请创建二叉树(#表示指针为空):\n");
      BiTNode T=InitDSTable();
      printf("中序遍历的结果为:\n");
      InOrderTravese(T);
      Count(T);
      printf("叶子结点数和非叶子结点的个数为:%d,%d",n1,n2);
     
      return 0;

}
4 回复
#2
yuccn2013-01-08 20:54
void Count(BiTNode T)
 {
      if(T == NULL) {
            return;
      }

      if(T->lchild==NULL && T->rchild==NULL)
          n1++; // 这个为叶子
      else
          n2++; // 非叶子 你的注释有误吧

      Count(T->lchild);
      Count(T->rchild);
 
}

[ 本帖最后由 yuccn 于 2013-1-8 20:58 编辑 ]
#3
不玩虚的2013-01-09 09:27
同上,注释有问题!
#4
yaobao2013-01-09 12:36
表示刚学数据结构,帮不上忙
#5
xinglinzhang2013-01-14 20:24
大神,我运行后,程序没问题。但运行到 BiTNode T=InitDSTable();这步后有问题了。麻烦把运行过程发下,谢谢!!
1