二叉树孩子链表法之找家人
题目描述
给出二叉树的孩子链表表示法,根据输入要求,找指定结点的双亲或孩子
输入
第一行输入两个参数,第一个参数n表示树有n个结点,第二个参数r表示根结点的数组下标
接着n行,每行先输入一个结点的数值(用单个字母表示),再输入结点的孩子下标(先左后右),如果只有一个孩子默认是左孩子,最后以-1结尾
如果该结点没有孩子,则一行只输入结点的数值和-1
接着输入t表示有t个结点要找家人
接着t行,每行输入两个参数,第1个参数是结点的数值,第2个参数是一个数字,其中0表示找双亲,1表示找左孩子,2表示找右孩子;
输出
输出t行,每行输出指定结点的双亲数值或孩子数值
每行输出一个数值,如果指定结点没有双亲或者没有孩子,则输出@
输入样例:
10 4
A 3 5 -1
B 2 9 -1
C 6 -1
D -1
R 0 1 -1
E -1
F 7 8 -1
G -1
H -1
K -1
4
G 0
R 1
C 2
R 0
输出样例:
F
A
@
@
参考代码:
#include <iostream>
#include <stack>
#include <vector>
#include <queue>
#include <list>
using namespace std;
struct Node {
char name;
int left_child_index = -1, right_child_index = -1;
};
int main() {
int n, r;
cin >> n >> r;
Node *arr = new Node[n];
for (int i = 0; i < n; ++i) {
cin >> arr[i].name;
int index;
cin >> index;
while (index != -1) {
if (arr[i].left_child_index == -1)
arr[i].left_child_index = index;
else if (arr[i].right_child_index == -1)
arr[i].right_child_index = index;
cin >> index;
}
}
int t;
cin >> t;
while (t--) {
char name;
int num;
cin >> name >> num;
if (num == 0) {
int flag = 0;
for (int i = 0; i < n; ++i)
if (arr[arr[i].left_child_index].name == name || arr[arr[i].right_child_index].name == name) {
cout << arr[i].name << endl;
flag = 1;
break;
}
if (!flag)
cout << '@' << endl;
} else if (num == 1) {
for (int i = 0; i < n; ++i)
if (arr[i].name == name) {
if (arr[i].left_child_index != -1)
cout << arr[arr[i].left_child_index].name << endl;
else
cout << '@' << endl;
break;
}
} else if (num == 2) {
for (int i = 0; i < n; ++i)
if (arr[i].name == name) {
if (arr[i].right_child_index != -1)
cout << arr[arr[i].right_child_index].name << endl;
else
cout << '@' << endl;
break;
}
}
}
return 0;
}