9059:链接存储转为顺序存储

版权声明:转载商用请通知本人 https://blog.csdn.net/qq_41076577/article/details/84567094

Problem Description

问题描述:设有一棵二叉树,其节点值为字符型并假设各值互不相等,采用二叉链表存储表示。现输入其扩展二叉树的前序遍历序列,建立该二叉链表,要求将该二叉树的二叉链表存储结构转换为顺序存储结构,并输出各数组元素,空二叉树用'#'表示。

 Input

第一行为一个整数n,表示以下有n组数据,每组数据占一行,为扩展二叉树的前序遍历序列,每组数据的长度不会超过50。

 Output

输出顺序存储表示时的各数组元素。

 Sample Input

3
AB#D##C##
ABD##E##C#F##
#

 Sample Output

ABC#D
ABCDE#F
#

 Author

hwt

 Recommend

zh

#include <iostream>
#include<string.h>
using namespace std;
#define max(i,j) i>j?i:j
 
typedef struct BiNode{
	char data;
	BiNode* lchild,* rchild;
}* BiTree;
 
char str[1111];
int num;   ///统计个数用的
BiTree t;
 
void Creat(BiTree& t,int x){
	t=new BiNode;
	char ch;
	cin>>ch;
	if(ch=='#')
		t=NULL;
	else{
		t->data=ch;
		num=max(x,num);   ///统计字符串个数 
		str[x]=ch;
		Creat(t->lchild,x<<1);   ///建立左子树
		Creat(t->rchild,x<<1|1);   ///建立右子树
	}
}
 
int main()
{
	int n;
	cin>>n;
	while(n--)
	{
		memset(str,'#',sizeof(str));
		num=0;
		Creat(t,1);
		if(t==NULL){   ///如果是空树,就输出井号
			cout<<"#\n";
			continue;
		}
		for(int i=1;i<=num;i++)
			cout<<str[i];
		cout<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41076577/article/details/84567094
今日推荐