问题 D: 二叉树遍历

问题 D: 二叉树遍历

时间限制: 1 Sec  内存限制: 32 MB
提交: 218  解决: 129
[提交][状态][讨论版][命题人:外部导入]

题目描述

编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。
例如如下的先序遍历字符串:
ABC##DE#G##F###
其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。

输入

输入包括1行字符串,长度不超过100。

输出

可能有多组测试数据,对于每组数据,
输出将输入字符串建立二叉树后中序遍历的序列,每个字符后面都有一个空格。
每个输出结果占一行。

样例输入

a#b#cdef#####
a##

样例输出

a b f e d c 
a 

accept code:

//#include <bits/stdc++.h>//codeup上万能的头文件编译不能通过 
#include <iostream>
#include <string.h>
using namespace std;
//char pre[120];
string pre; 
struct node{
	char data;
	node* lchild;
	node* rchild;
};

node* create(int &prel)//需要使用引用,否则的话只能前半部分正确,递归到最后的几个#####时会出现下表混乱的情况 
{
	if(pre[prel]=='#')return NULL;
	
	node* root=new node;
	root->data=pre[prel];
//	cout<<prel<<"&&";
//	cout<<root->data<<"*";
	root->lchild=create(++prel);
	root->rchild=create(++prel); 
	return root;//返回的是最开始创建的那个根结点的地址
}
void inorder(node* root)
{
	if(root==NULL)
	{
		return;
	}
	inorder(root->lchild);
	printf("%c ",root->data);
	inorder(root->rchild);
}
int main()
{
	while(cin>>pre)
	{
		int x=0;
		node* root=create(x);//上面的参数用引用的话此处不能直接用0,会报参数类型不一致的错误。因为0不会分配地址,而引用要用到地址 
		inorder(root);
		cout<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38938670/article/details/89105238