首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >标准BST二叉搜索树写法

标准BST二叉搜索树写法

作者头像
用户2038589
发布2018-09-06 11:39:11
4830
发布2018-09-06 11:39:11
举报

  本人最近被各种数据结构的实验折磨的不要不要的,特别是代码部分,对数据结构有严格的要求,比如写个BST要分成两个类,一个节点类,要给树类,关键是所以操作都要用函数完成,也就是在树类中不能直接操作节点,需要使用节点类中的函数来实现各种操作。

  简直太麻烦,但是花时间写了也是有好处的,认真写完绝对几年忘不了。同时用函数操作数据也更安全,将数据设为私有成员更符合规范。下面给出代码。

 1 #include<iostream>
 2 using namespace std;
 3 
 4 class BinNode {
 5 private:
 6     int element;
 7     BinNode *leftChild;
 8     BinNode *rightChild;
 9 public:
10         BinNode(int a, BinNode* left, BinNode* right) {
11         element = a;
12         leftChild = left;
13         rightChild = right;
14     }
15     int val() { return element; }
16     BinNode* left() { return leftChild; }
17     void setLeft(BinNode *t) {  leftChild=t; }
18     BinNode* right() { return rightChild; }    
19     void setRight(BinNode *t) { rightChild = t; }
20 };
21 class BST{
22 private:
23     BinNode *root;
24      BinNode* insertHelp(int x, BinNode* root) {
25          BinNode* t = root;
26          if (t == NULL) { t = new BinNode(x, NULL, NULL); return t; }
27         else if (x < t->val())
28             t->setLeft(insertHelp(x, t->left()));
29         else if (x > t->val())
30             t->setRight(insertHelp(x, t->right()));
31         return t;
32     }
33     void findHelp(const int x, int &count, BinNode* root) {
34         count++;
35         if (root == NULL) { count = 0;return; }
36         else if (root->val() == x)  return;
37         if(x<root->val())
38             findHelp(x, count, root->left());
39         if(x>=root->val())
40         findHelp(x, count, root->right());
41     }
42 public:
43     BST() {    root = NULL;}
44     ~BST() { clear(root);}
45 
46     void clear(BinNode *root) {
47         if (root != NULL) {
48             clear(root->left());
49             clear(root->right());
50             delete root;
51         }
52     }
53     void insert(int& x) {
54         root=insertHelp(x, root);
55     }
56     void find(const int x, int &count) {
57         findHelp(x, count, root);
58     }
59 };
60 int main() {
61     BST a;
62     int n;
63     cout << "请输入节点个数:" << endl;
64     cin >> n;
65     cout << "依次输入节点值:"<<endl;
66     for (int i = 0;i < n;i++) {
67         int x;cin >> x;
68         a.insert(x);
69     }
70     int num;
71     while ((cout << "请输入需要查找的值:(ctrl+z结束查找)" << endl)&&(cin>>num)&&num!=EOF){
72         int count=0;
73         a.find(num, count);
74         if (count == 0)
75             cout << "查找失败!" << endl;
76         else
77             cout << "查找成功!查找次数为:" << count << endl;
78     }
79     system("pause");
80     return 0;
81 }

下面是实验报告的文档地址

http://wenku.baidu.com/view/d97fb2b114791711cd791711

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-12-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档