为啥我二叉树创建好之后,传到遍历方法中,输出就不对呢
贴代码图和问题图
用c语言写的先序创建二叉树,纠结半天了。劳请各位看看
#include
#include
#include
typedef struct TreeNode{
char data;
struct TreeNode *lchild;
struct TreeNode *rchild;
}TreeNode;
void pf(TreeNode *treeList){
printf("根地址:%d\n",treeList);
if(treeList!=NULL){
printf("根结点:%c\n",treeList->data);
pf(treeList->lchild);
pf(treeList->rchild);
}
}
TreeNode* create(TreeNode *treeList){
char value;
printf("请输入一个字符\n");
scanf(" %c",&value);//注意啊,回车也会被当作一个字符
if(value=='#'){
treeList=NULL;
}else{
treeList=(TreeNode *)malloc(sizeof(TreeNode));
treeList->data=value;
printf("输出没问题啊:%c,%d\n",treeList->data,treeList);
create(treeList->lchild);
create(treeList->rchild);
}
return treeList;
}
int main(){
TreeNode *treeList;
treeList=(TreeNode*)malloc(sizeof(TreeNode));
treeList->lchild=NULL;
treeList->rchild=NULL;
treeList=create(treeList);
printf("根结点:%c,%d\n",treeList->data,treeList);
pf(&treeList);
}
你这代码中,在遍历函数 pf 中传入了二叉树的根结点的地址,但是在打印输出时,使用了 treeList 这个指针变量本身的值,而不是它所指向的地址中的值。
在 C 语言中,可以通过在变量前加上一个 * 号来访问指针变量所指向的内存地址中的值。
例如可以将代码中的
printf("根结点:%c\n",treeList->data);
改为
printf("根结点:%c\n",(*treeList).data);
或者
printf("根结点:%c\n",*treeList.data);
来访问根结点中的数据。
可以在遍历函数中对每个结点都使用类似的方法来访问它们的数据。
另外在代码中,使用了 scanf 函数来输入字符,但是 scanf 函数会读取空格和回车符,因此在输入字符时可能会出现问题。
可以使用 getchar 函数来输入字符,这样就可以避免上述问题了。
例如可以将代码中的
scanf(" %c",&value);
改为
value = getchar();
来输入字符。
仅供参考,望采纳,谢谢。
修改如下,改动处见注释,供参考:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct TreeNode{
char data;
struct TreeNode *lchild;
struct TreeNode *rchild;
}TreeNode;
void pf(TreeNode *treeList){
if(treeList!=NULL){
printf("根结点:%c\n",treeList->data); //修改
printf("根地址:%p\n",treeList); //修改
//printf("根地址:%d\n",treeList); 修改
pf(treeList->lchild);
pf(treeList->rchild);
}
}
TreeNode* create(TreeNode *treeList){
char value;
printf("请输入一个字符\n");
scanf(" %c",&value);//注意啊,回车也会被当作一个字符
getchar();
if(value=='#'){
treeList=NULL;
}else{
treeList=(TreeNode *)malloc(sizeof(TreeNode));
treeList->data=value;
printf("输出没问题啊:%c,%p\n",treeList->data,treeList); //修改
//printf("输出没问题啊:%c,%d\n",treeList->data,treeList);
treeList->lchild = create(treeList->lchild); //修改
treeList->rchild = create(treeList->rchild); //修改
}
return treeList;
}
int main(){
TreeNode *treeList;
//treeList=(TreeNode*)malloc(sizeof(TreeNode)); 修改
//treeList->lchild=NULL;
//treeList->rchild=NULL;
treeList=create(treeList);
printf("根结点:%c,%p\n",treeList->data,treeList); //修改
//printf("根结点:%c,%d\n",treeList->data,treeList);
pf(treeList); //修改
// pf(&treeList);
return 0;
}