层次建立二叉树遍历出错


tree *creat2()//逐层建立二叉树
{
	tree* qnode[100];
	char ch;
	int i=0;
	ch=getchar();
	while(ch!='#')
	{
		i=i+1;
		qnode[i]=(tree*)malloc(sizeof(tree));
		qnode[i]->x=ch;
		ch=getchar();
	
	}
    
	for(int n=1;n<=i;++n)
	{
		if(n==1)
		{
			qnode[n]->L=0;
			qnode[n]->R=0;
		}
	   else if(n%2==0)
		{
			qnode[n/2]->L=qnode[n];
		}
	   else if(n%2!=0)
	   {
	   		qnode[n/2]->R=qnode[n];
	   }
       
		
	}
	
	return qnode[1];
} 
 

oid preread(tree*& b)//前序遍历 
{
	

	if(b!=0)
	{
		cout<<(*b).x;
		preread(b->L);
		preread(b->R);
	}
	
}




int main()
{
	tree* t;
	t=creat2();
	
	preread(t);
}

遍历时右叉树数据出不来,是其他的汉字

帮你把错误改了,可以运行了。你看结果是不是你想要的。你自己继续调试,权当练身手吧


#include <stdio.h>
#include <stdlib.h>

typedef struct tree
{
    char x;
    struct tree* L;
    struct tree* R;
} tree;

tree *creat2()//逐层建立二叉树
{
	tree* qnode[100];
	char ch;
	int i=0;
	ch=getchar();
	while(ch!='#')
	{
		i=i+1;
		qnode[i]=(tree*)malloc(sizeof(tree));
		qnode[i]->x=ch;
		ch=getchar();
	
	}
	for(int n=1;n<=i;++n)
	{
		if(n==1)
		{
			qnode[n]->L=0;
			qnode[n]->R=0;
		}
	   else if(n%2==0)
		{
			qnode[n/2]->L=qnode[n];
		}
	   else if(n%2!=0)
	   {
	   		qnode[n/2]->R=qnode[n];
	   }
		
	}
	
	return qnode[1];
} 
void preread(tree*& b)//前序遍历 
{
	
	if(b!=0)
	{
		printf("%c", (*b).x);
		preread(b->L);
		preread(b->R);
	}
	
}
int main()
{
	tree* t;
	t=creat2();
	
	preread(t);
}

// Output
abcdefghijklmnopqrstuvwxyz#                                                                                                                            
abdhpqirsejtukvwcflxymzgno

 

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632