本專欄持續輸出數據結構題目集,歡迎訂閱。
文章目錄
- 題目
- 代碼
題目
請編寫程序,創建有 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;// 初始化子節點為NULLfor (int i = 0; i < 3; i++) {node->children[i] = NULL;}return node;
}// 遞歸查找節點
int findNode(TreeNode* root, int x) {// 若當前節點為空,返回0if (root == NULL) {return 0;}// 若當前節點的鍵值等于x,返回1if (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); // 根的第三個孩子// 讀取待查找的值xint 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;
}