【PTA数据结构 | C语言版】查找树中带有指定数据的结点

本专栏持续输出数据结构题目集,欢迎订阅。

文章目录

题目

请编写程序,创建有 4 个结点的树,然后查找给定的 x。

输入格式:
输入首先在第一行给出 4 个正整数,依次对应树的根结点、根的第 1、2、3 个孩子结点的键值。第二行给出待查找的 x 的值。所有键值均为 int 型范围内的整数,同行数字间以空格分隔。

输出格式:
如果 x 在树中存在,则在一行中输出 x is found.;否则输出 x is NOT found.。

输入样例 1:
1 2 3 4
4

输出样例 1:
4 is found.

输入样例 2:
5 6 7 8
4

输出样例 2:
4 is NOT found.

代码

#include <stdio.h>
#include <stdlib.h>

// 定义树节点结构
typedef struct TreeNode {
    int key;
    struct TreeNode* children[3];  // 最多3个子节点
} TreeNode;

// 创建新节点
TreeNode* createNode(int key) {
    TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
    node->key = key;
    // 初始化子节点为NULL
    for (int i = 0; i < 3; i++) {
        node->children[i] = NULL;
    }
    return node;
}

// 递归查找节点
int findNode(TreeNode* root, int x) {
    // 若当前节点为空,返回0
    if (root == NULL) {
        return 0;
    }
    // 若当前节点的键值等于x,返回1
    if (root->key == x) {
        return 1;
    }
    // 递归查找子节点
    for (int i = 0; i < 3; i++) {
        if (findNode(root->children[i], x)) {
            return 1;
        }
    }
    // 未找到
    return 0;
}

int main() {
    int rootKey, c1, c2, c3;
    // 读取4个节点的键值
    scanf("%d %d %d %d", &rootKey, &c1, &c2, &c3);
    
    // 创建树结构
    TreeNode* root = createNode(rootKey);
    root->children[0] = createNode(c1);  // 根的第一个孩子
    root->children[1] = createNode(c2);  // 根的第二个孩子
    root->children[2] = createNode(c3);  // 根的第三个孩子
    
    // 读取待查找的值x
    int x;
    scanf("%d", &x);
    
    // 查找x是否在树中
    if (findNode(root, x)) {
        printf("%d is found.\n", x);
    } else {
        printf("%d is NOT found.\n", x);
    }
    
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

秋说

感谢打赏

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

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

打赏作者

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

抵扣说明:

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

余额充值