用二叉搜索树来实现数据的存储与访问(C++)

递归实现二叉搜索树多的插入与搜索

上代码~~

 1 #pragma warning(disable:4996)
 2 #include<iostream>
 3 using namespace std;
 4 
 5 struct BSTnode
 6 {
 7     int data;
 8     BSTnode* left;
 9     BSTnode* right;
10 };
11 
12 BSTnode* getnewnode( int data)//一开始写还写多了一个参数 BSTnode* root
13 {
14     //用c写 BSTnode* newnode = (BSTnode*) malloc (sizeof(BSTnode)
15     BSTnode* newnode = new BSTnode(); //一开始写成了 root = new BSTnode();
16     newnode->data = data;
17     newnode->left = NULL;
18     newnode->right = NULL;
19     return newnode;
20 }
21 BSTnode* insert(BSTnode* root, int data)
22 {
23     if (NULL == root)
24     {
25         root = getnewnode(data);
26         return root; // 一开始没写这句
27     }
28     else if (data <= root->data)
29         root->left = insert(root->left, data);
30     else
31         root->right = insert(root->right, data);//一开始写没写root->left和root->right
32     return root;
33 }
34 
35 bool search(BSTnode* root,int data)
36 {
37     if (NULL == root)
38         return false;
39     else if (data == root->data)
40         return true;
41     else if (data <= root->data)
42         return search(root->left, data);
43     else
44         return search(root->right, data);//一开始写没写return
45 }
46 
47 int main()
48 {
49     BSTnode* root = NULL;
50     root = insert(root, 1);//一开始没写左边的root
51     root = insert(root, 2);
52     root = insert(root, 3);
53     root = insert(root, 4);
54     root = insert(root, 5);
55     root = insert(root, 6);
56     root = insert(root, 7);
57     int number;
58     cout << "Enter the number which you want to serch:" << "\n";
59     cin >> number;
60     if (search(root, number) == true)
61         cout << "Found!";
62     else
63         cout << "This number is not in this tree";
64 }
65 /*讲真,看视频后自己敲了一遍,还是错漏百出,之前看过一遍觉得自己已经懂了,
66 其实是自己骗自己,再加上早上很困,状态也不好(别为自己找借口了,菜就是菜,
67 多点敲代码,让敲代码尽早的成为一项体力活吧*/

 

posted @ 2021-11-03 23:14  越菜越自信  阅读(67)  评论(0)    收藏  举报