标准BST二叉搜索树写法
2015-12-08 00:08
429 查看
本人最近被各种数据结构的实验折磨的不要不要的,特别是代码部分,对数据结构有严格的要求,比如写个BST要分成两个类,一个节点类,要给树类,关键是所以操作都要用函数完成,也就是在树类中不能直接操作节点,需要使用节点类中的函数来实现各种操作。
简直太麻烦,但是花时间写了也是有好处的,认真写完绝对几年忘不了。同时用函数操作数据也更安全,将数据设为私有成员更符合规范。下面给出代码。
View Code
下面是实验报告的文档地址
http://wenku.baidu.com/view/d97fb2b114791711cd791711
简直太麻烦,但是花时间写了也是有好处的,认真写完绝对几年忘不了。同时用函数操作数据也更安全,将数据设为私有成员更符合规范。下面给出代码。
#include<iostream> using namespace std; class BinNode { private: int element; BinNode *leftChild; BinNode *rightChild; public: BinNode(int a, BinNode* left, BinNode* right) { element = a; leftChild = left; rightChild = right; } int val() { return element; } BinNode* left() { return leftChild; } void setLeft(BinNode *t) { leftChild=t; } BinNode* right() { return rightChild; } void setRight(BinNode *t) { rightChild = t; } }; class BST{ private: BinNode *root; BinNode* insertHelp(int x, BinNode* root) { BinNode* t = root; if (t == NULL) { t = new BinNode(x, NULL, NULL); return t; } else if (x < t->val()) t->setLeft(insertHelp(x, t->left())); else if (x > t->val()) t->setRight(insertHelp(x, t->right())); return t; } void findHelp(const int x, int &count, BinNode* root) { count++; if (root == NULL) { count = 0;return; } else if (root->val() == x) return; if(x<root->val()) findHelp(x, count, root->left()); if(x>=root->val()) findHelp(x, count, root->right()); } public: BST() { root = NULL;} ~BST() { clear(root);} void clear(BinNode *root) { if (root != NULL) { clear(root->left()); clear(root->right()); delete root; } } void insert(int& x) { root=insertHelp(x, root); } void find(const int x, int &count) { findHelp(x, count, root); } }; int main() { BST a; int n; cout << "请输入节点个数:" << endl; cin >> n; cout << "依次输入节点值:"<<endl; for (int i = 0;i < n;i++) { int x;cin >> x; a.insert(x); } int num; while ((cout << "请输入需要查找的值:(ctrl+z结束查找)" << endl)&&(cin>>num)&&num!=EOF){ int count=0; a.find(num, count); if (count == 0) cout << "查找失败!" << endl; else cout << "查找成功!查找次数为:" << count << endl; } system("pause"); return 0; }
View Code
下面是实验报告的文档地址
http://wenku.baidu.com/view/d97fb2b114791711cd791711
相关文章推荐
- 浅谈C语言中scanf(),gets()函数区别与联系
- servlet向jsp传数据
- 经典冒泡排序法
- git版本控制开发流程小结笔记(一)
- C#的Activator.CreateInstance方法
- 超链算法升级 百度站长平台拒绝外链工具将下线
- 1 秒内启动Linux的方法
- Linux下启动tomcat的方法
- js正则表达式学习笔记
- js正则表达式常用函数详解
- js正则表达式常用函数详解(续)
- Python使用pygame模块编写俄罗斯方块游戏的代码实例
- 一波神奇的Python语句、函数与方法的使用技巧总结
- 使用Python编写简单的画图板程序的示例教程
- PHP使用MPDF类生成PDF的方法
- PHP MPDF中文乱码的解决方式
- 如何使用GDB调试PHP程序
- 学习php设计模式 php实现合成模式(composite)
- 学习php设计模式 php实现命令模式(command)
- mysql 创建表时以UTF8编码