树结构转换(先序转双亲)

题目描述

给出一棵二叉树的特定字符先序遍历结果(空子树用字符'#'表示),构建该二叉树,并输出该二叉树的双亲表示法结果

双亲表示法的数组下标从0开始,根结点必定是在下标0元素,且根结点的双亲下标为-1,左右孩子按下标递增顺序排列,

结点下标是层次遍历顺序。

输入

第一个输入t,表示有t棵二叉树

接着t行,每行输入含特定字符的二叉树先序遍历序列

输出

共输出2t行

每棵二叉树输出两行,第一行输出各个结点的数值,第二行输出各结点的双亲下标

输入:
3
AB#C##D##
ABD##E##C##
AB##CDW###E#F##
输出:
A B D C
-1 0 0 1
A B C D E
-1 0 0 1 1
A B C D E W F
-1 0 0 2 2 3 4
#include<iostream>
#include<queue>
using namespace std;
int cnt = 0;
int x[100] = { -1 };
char y[100] = { '0'};
char father[100] = { '0' };
typedef struct BiNode
{
	char name;
	char fatherName;
	BiNode* lchild, * rchild;
}*BiTree;
BiTree initBiNode()
{
	BiTree T;
	T = new BiNode;
	T->lchild = NULL;
	T->rchild = NULL;
	return T;
}
void CreatBiTree(BiTree& T,char name)
{
	char ch;  cin >> ch;
	if (ch == '#') { T = NULL; }
	else
	{
		T = new BiNode;
		T->name = ch;
		T->fatherName = name;
		CreatBiTree(T->lchild,T->name);
		CreatBiTree(T->rchild,T->name);
	}
}
void LeveLOrder(BiTree& T)
{
	queue<BiTree>Q;
	BiTree S = T;
	if (S)Q.push(S);
	int i = 0,j=0;
	while (!Q.empty())
	{
		S = Q.front();
		Q.pop();
		if (S)
		{
			cnt++;
			y[i++] = S->name;
			father[j++] = S->fatherName;
			if (S->lchild != NULL) Q.push(S->lchild);
			if (S->rchild != NULL) Q.push(S->rchild);
		}
	}
}
void GetX()
{
	x[0] = -1;
	for (int i = 1; i < cnt; i++)
	{
		for (int j = 0; j < cnt; j++)
		{
			if (father[i] == y[j])x[i] = j;
		}
	}
}
int main()
{
	int t; cin >> t;
	while (t--)
	{
		cnt = 0;
		BiTree mytree;
		CreatBiTree(mytree,'-1');
		LeveLOrder(mytree);
		GetX();
		for (int i = 0; i < cnt; i++)
		{
			cout << y[i];
			if (i == cnt - 1)cout << endl;
			else cout << " ";
		}
		for (int i = 0; i < cnt; i++)
		{
			cout << x[i];
			if (i == cnt - 1)cout << endl;
			else cout << " ";
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值