资源简介
定义二叉搜索树类,封装查找、插入、删除操作;
代码片段和文件信息
#include
using namespace std;
template
class BinaryTreeNode
{
public:
T element;
BinaryTreeNode *leftChild;
BinaryTreeNode *rightChild;
BinaryTreeNode() {}
~BinaryTreeNode()
{
if (leftChild) delete leftChild;
if (rightChild) delete rightChild;
}
};
template
void create(BinaryTreeNode** root)
{
T temp;
cin >> temp;
if (temp == 0)
{
*root = NULL;
}
else {
*root = new BinaryTreeNode;
(*root)->element = temp;
create(&((*root)->leftChild));
create(&((*root)->rightChild));
}
}
int flag = 0;
template
BinaryTreeNode* search(BinaryTreeNode*rootT key)
{
BinaryTreeNode* current = root;
while ((NULL) != root && (key != current->element))
{
current = (key < current->element ? search(current->leftChild key) : search(current->rightChild key));
if (current == NULL)break;
}
return current;
}
template
BinaryTreeNode* getParent(BinaryTreeNode*root BinaryTreeNode*current)
{
BinaryTreeNode*temp = root;
BinaryTreeNode*temp2 = root;
while (temp)
{
if (current->element > temp->element)
{
temp2 = temp;
temp = temp->rightChild;
}
if (current->element < temp->element)
{
temp2 = temp;
temp = temp->leftChild;
}
if (current->element == temp->element)
{
return temp2;
}
}
return NULL;
}
template
void insertNode(BinaryTreeNode*rootconst T &value)
{
BinaryTreeNode*p = root *prev = NULL;
while (p!=NULL)
{
prev = p;
if (p->element < value)
p = p->rightChild;
else
p = p->leftChild;
}
if (root == NULL)
{
root = new BinaryTreeNode;
root->element = value;
}
else if (prev->element < value)
{
prev->rightChild = new BinaryTreeNode;
prev->rightChild->element = value;
}
else {
prev->leftChild = new BinaryTreeNode;
prev->leftChild->element = value;
}
}
template
void deleteNode(BinaryTreeNode*rootconst T &value)
{
BinaryTreeNode*node=search(rootvalue);
if (node == NULL)
{
cout << “没有这个元素“ << endl;
}
if (value == root->element)
{
BinaryTreeNode*temp = root->leftChild;
while (temp->rightChild != NULL)
{
temp = temp->rightChild;
}
BinaryTreeNode*temp2 = getParent(roottemp);
root->element = temp->element;
temp2->rightChild = temp->leftChild;
}
else
{
BinaryTreeNode*prevNode = getParent(root node);//删除结点前一节点
int flag = 0;
if (prevNode->leftChild == node)
flag = 1;
BinaryTreeNode*tmp = nod
- 上一篇:C语言 车辆出租管理系统
- 下一篇:北京地铁最短路径.rar
相关资源
- 国际象棋的qt源代码
- C++中头文件与源文件的作用详解
- C++多线程网络编程Socket
- VC++ 多线程文件读写操作
- 利用C++哈希表的方法实现电话号码查
- 移木块游戏,可以自编自玩,vc6.0编写
- C++纯文字DOS超小RPG游戏
- 学校超市选址问题(数据结构C语言版
- VC++MFC小游戏实例教程(实例)+MFC类库
- 数据结构,迷宫问题C语言版源代码
- DSDEMO-C演示(数据结构C语言版 严蔚敏
- 连铸温度场计算程序(C++)
- 6自由度机器人运动学正反解C++程序
- Em算法(使用C++编写)
- libstdc++-4.4.7-4.el6.i686.rpm
- VC++实现CMD命令执行与获得返回信息
- 白话C++(全)
- C++标准库第1、2
- 大数类c++大数类
- C++语言编写串口调试助手
- c++素数筛选法
- C++ mqtt 用法
- 商品库存管理系统 C++ MFC
- c++ 多功能计算器
- C++17 In Detail
- 嵌入式QtC++编程课件
- 颜色识别形状识别STM103嵌入式代码
- 数据结构 图的遍历源代码
- 数据结构实验源代码集
- 实验报告:数据结构长整数四则运算
评论
共有 条评论