题目描述
给出一棵二叉树的特定字符先序遍历结果(空子树用字符'#'表示),构建该二叉树,并输出该二叉树的双亲表示法结果
双亲表示法的数组下标从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 << " ";
}
}
}