二叉树遍历崩溃求大神帮我分析分析
#include <stdio.h>
#include <stdlib.h>
typedef struct BiTNode//
{
char data;
struct BiTNode *rchild;
struct BiTNode *lchild;
} BiTNode,*BiTree;
void CreateBiTree(BiTree *T)//先序创建二叉树
{
char ch;
scanf("%c",&ch);
if(ch=='#')
(*T)==NULL;
else
{
(*T)=(BiTNode* )malloc(sizeof(BiTNode));
(*T)->data=ch;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
void InOrderTraverse( BiTree T)//中序遍历输出
{
if(T!=NULL)
InOrderTraverse(T->lchild);
printf("%c",T->data);
InOrderTraverse(T->rchild);
}
int NodeCount(const BiTree T)//计算元素个数
{
if(T==NULL) return 0;
else return NodeCount(T->lchild)+NodeCount(T->rchild)+1;
}
int main() //主函数
{
BiTree T;
printf("按先序依次输入字符:\n");
CreateBiTree(&T);
printf("创建成功\n");
printf("\n\n中序遍历二叉树结果:\n");
InOrderTraverse(T);
printf("\n遍历成功\n");
printf("\n\n元素个数为:%d\n",NodeCount(T));
}
以下是我同学的代码可以跑
typedef struct BitNode
{
char data;
struct BitNode *Rchild;
struct BitNode *Lchild;
} BiTNode,*BiTree;
void CreateBiTree(BiTree *T)
{
char ch;
scanf("%c",&ch);
if(ch == '#')
{
*T = NULL;
}
else
{
*T = (BiTree)malloc(sizeof(BiTNode));
(*T)->data = ch;
CreateBiTree(&(*T)->Lchild);
CreateBiTree(&(*T)->Rchild);
}
}
//二叉树的中序遍历
void InOrderTraverse(BiTree T)
{
if(T == NULL) return;
InOrderTraverse(T->Lchild);
printf("%c ",T->data);
InOrderTraverse(T->Rchild);
}
//求二叉树的节点个数
int NodeCount ( BiTree T)
{
if(T==NULL) return 0;
else return NodeCount(T->Lchild) + NodeCount(T->Rchild) + 1;
}
main()
{
printf("请输入节点信息\n");
BiTree T;
CreateBiTree(&T);
printf("\n\n中序遍历结果为 :\n");
InOrderTraverse(T);
printf("\n\n二叉树的节点个数为:\n%d\n", NodeCount(T));
return 0;
}
实在是看不出哪里有什么不同
首先问题在于你的
CreateBiTree
方法。方法
InOrderTraverse
也存在问题。如果
T
没有左孩子,但他存在,那么在下面的printf("%c", T->data)
中就会因为找不到对应的data
而发生错误。你同学写的是正确的。