二叉树孩子链表法之找家人

二叉树孩子链表法之找家人

题目描述

给出二叉树的孩子链表表示法,根据输入要求,找指定结点的双亲或孩子

输入

第一行输入两个参数,第一个参数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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鷸鰥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值