博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【数据结构周周练】021 求某一个数据在二叉排序树中的层数
阅读量:4076 次
发布时间:2019-05-25

本文共 1791 字,大约阅读时间需要 5 分钟。

一、二叉排序树

今天给大家分享的是二叉排序树的应用,判断一个数据在二叉排序树中的层数。

我们这个算法原理比较简单,就是循环做判断,当数据小于树中结点数据时,判断左子树;大于树中结点数据时,判断右子树;等于树中结点数据时,输出;当查找到树为空还找不到时,返回错误。

下面就是我们给定的二叉排序树及所有的代码。

二、示例

给定一个数据,判断该数据是否为二叉排序树中的数据并求其所在层数。其中圆角矩形内为结点数据,旁边数字为结点编号,箭头指向的结点为箭尾的孩子结点。

二叉排序树

 三、代码

#include
#include
using namespace std;typedef struct BiSTNode { int data; int number; struct BiSTNode *lChild, *rChild;}BiSTNode,*BiSortTree;int numData[] = { 12,5,11,67,55,45,57,72 };int length = sizeof(numData) / sizeof(int);int number = 0;int OperationBiSortTree(BiSortTree &BST,int data) { BST = (BiSortTree)malloc(sizeof(BiSTNode)); if (!BST) { cout << "空间分配失败(Allocate space failure.)" << endl; exit(OVERFLOW); } BST->data = data; BST->number = number++; BST->lChild = NULL; BST->rChild = NULL; return 1;}int EstablishBiSortTree(BiSortTree &BST) { BiSortTree p = BST; if (!BST) { OperationBiSortTree(BST, numData[number]); } else if (BST->data == numData[number]) { cout << "This data \" " << BST->data << " \" is existing.\n"; number++; return 0; } else if (BST->data > numData[number]) EstablishBiSortTree(BST->lChild); else EstablishBiSortTree(BST->rChild); return 1;}void InOrderVisitTree(BiSortTree BST) { if (BST->lChild) InOrderVisitTree(BST->lChild); cout << BST->data << " , "; if (BST->rChild) InOrderVisitTree(BST->rChild);}int FindLevel(BiSortTree BST,int data) { BiSortTree pT = BST; int level = 1; while (pT && pT->data != data) { if (pT->data > data) pT = pT->lChild; else pT = pT->rChild; level++; } if (pT) { cout << "This binary sort tree has the data : " << pT->data << " , and the level is " << level << ";\n"; return 1; } else { cout << "This binary sort tree doesn't have the data : " << data << endl; return 0; } }void main() { BiSortTree BST = NULL; while (number

四、实现效果

转载地址:http://odyni.baihongyu.com/

你可能感兴趣的文章
《数据库系统概论》 第二章 关系数据库
查看>>
《数据库系统概论》 第三章 关系数据库标准语言SQL
查看>>
SQL语句(二)查询语句
查看>>
SQL语句(六) 自主存取控制
查看>>
《计算机网络》第五章 运输层 ——TCP和UDP 可靠传输原理 TCP流量控制 拥塞控制 连接管理
查看>>
堆排序完整版,含注释
查看>>
二叉树深度优先遍历和广度优先遍历
查看>>
生产者消费者模型,循环队列实现
查看>>
PostgreSQL代码分析,查询优化部分,process_duplicate_ors
查看>>
PostgreSQL代码分析,查询优化部分,canonicalize_qual
查看>>
PostgreSQL代码分析,查询优化部分,pull_ands()和pull_ors()
查看>>
IA32时钟周期的一些内容
查看>>
获得github工程中的一个文件夹的方法
查看>>
《PostgreSQL技术内幕:查询优化深度探索》养成记
查看>>
PostgreSQL查询优化器详解之逻辑优化篇
查看>>
STM32中assert_param的使用
查看>>
C语言中的 (void*)0 与 (void)0
查看>>
vu 是什么
查看>>
io口的作用
查看>>
IO口的作用
查看>>