1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| #include <stdio.h> #include <stdlib.h> struct BstNode { int data; BstNode* left; BstNode* right;
};
struct BstNode* root;
BstNode* GetNewnode(int data) { struct BstNode* newNode = (struct BstNode*)malloc(sizeof(struct BstNode)); newNode->data = data; newNode->left = NULL; newNode->right = NULL; return newNode; } BstNode* Insert(BstNode* root,int data) { if (root == NULL) { root = GetNewnode(data); } else if (data <= root->data) { root->left = Insert(root->left, data); } else { root->right = Insert(root->right, data); } return root; } bool Search(BstNode* root, int data) { if (root == NULL) return false; else if (data == root->data) return true; else if (data <= root->data) return Search(root->left, data); else return Search(root->right, data); } int main() { int number; root = NULL; root = Insert(root, 10); root = Insert(root, 25); root = Insert(root, 30); root = Insert(root, 13); printf("请输入你想查找的数字:"); scanf("%d", &number); if (Search(root, number)) printf("存在!"); else printf("不存在!");
return 0; }
|