本专栏持续输出数据结构题目集,欢迎订阅。
题目
请编写程序,创建有 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;
}