树结构转换(先序转双亲)
题目描述
给出一棵二叉树的特定字符先序遍历结果(空子树用字符’#'表示),构建该二叉树,并输出该二叉树的双亲表示法结果
双亲表示法的数组下标从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;
class BiTreeNode {
private:
char data;
BiTreeNode *left_child;
BiTreeNode *right_child;
BiTreeNode *parent;
public:
BiTreeNode() : data(' '), left_child(nullptr), right_child(nullptr), parent(nullptr) {}
friend class BiTree;
};
class BiTree {
private:
BiTreeNode *root;
BiTreeNode *a[1000];
int b[1000];
int len;
void Create(BiTreeNode *&t, BiTreeNode *par) {
char ch;
cin >> ch;
if (ch != '#') {
t = new BiTreeNode;
t->data = ch;
t->parent = par;
Create(t->left_child, t);
Create(t->right_child, t);
} else
t = nullptr;
}
int find(BiTreeNode *t) {
if (t == nullptr)
return -1;
for (int i = 0; i < 1000; i++) {
if (t == a[i])
return i;
}
}
public:
void Create() {
Create(root, nullptr);
}
void BFS() {
queue<BiTreeNode *> q;
int index = 0;
if (root != nullptr) {
q.push(root);
while (!q.empty()) {
a[index] = q.front();
b[index] = find(q.front()->parent);
index++;
if (q.front()->left_child != nullptr)
q.push(q.front()->left_child);
if (q.front()->right_child != nullptr)
q.push(q.front()->right_child);
q.pop();
}
}
len = index;
}
void display() {
for (int i = 0; i < len; i++) {
cout << a[i]->data;
if (i == len - 1)
cout << endl;
else
cout << " ";
}
for (int i = 0; i < len; i++) {
cout << b[i];
if (i == len - 1)
cout << endl;
else
cout << " ";
}
}
};
int main() {
int t;
cin >> t;
while (t--) {
BiTree tree{};
tree.Create();
tree.BFS();
tree.display();
}
return 0;
}