博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【数据结构周周练】019 利用递归算法创建二叉排序树并遍历
阅读量:4077 次
发布时间:2019-05-25

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

 一、二叉排序树

从今天起,就给大家分享二叉排序树的代码啦,首先给大家简单讲解一下相关概念。

二叉排序树也称为二叉查找树,二叉排序树是一棵空树或具有如下性质:

(1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值;

(2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值;

(3)左、右子树也分别为二叉排序树;

(4)没有键值相等的节点。

二叉排序树有这样一个特点:左子树结点值<根结点<右子树结点。所以对二叉树进行中序遍历会得到一个递增的序列。

废话不多说,接下来上代码,本次给大家分享的是二叉排序树的创建及遍历。

 

二、示例

利用递归算法将下列一组数据存入二叉排序树中,通过先序及中序遍历访问每个结点的编号,数据及所有的孩子结点。

{ 41,22,14,35,56,23,47,28,69,10,61,12 }

三、代码

#include
#include
using namespace std;typedef struct BiSTNode { int data; int number; struct BiSTNode *lChild, *rChild, *parent;}BiSTNode,*BiSortTree;int numData[] = { 41,22,14,35,56,23,47,28,69,10,61,12 };int length = sizeof(numData) / sizeof(int);int number = 0;BiSortTree treeParent = NULL;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 VisitBiSortTree(BiSortTree &BST) { cout << "The number of present node is :" << BST->number << "; "; cout << "\tdata is :" << BST->data << "; "; if (BST->lChild) cout << "\n\tlChild's number is :" << BST->lChild->number << ",\tdata is :" << BST->lChild->data << ";"; if (BST->rChild) cout << "\n\trChild's number is :" << BST->rChild->number << ",\tdata is :" << BST->rChild->data << ";"; cout << endl;}void PreOrderVisitTree(BiSortTree &BST) { VisitBiSortTree(BST); if (BST->lChild) PreOrderVisitTree(BST->lChild); if (BST->rChild) PreOrderVisitTree(BST->rChild);}void InOrderVisitTree(BiSortTree &BST) { if (BST->lChild) InOrderVisitTree(BST->lChild); VisitBiSortTree(BST); if (BST->rChild) InOrderVisitTree(BST->rChild);}void main() { BiSortTree BST = NULL; while (number

四、实现效果

 

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

你可能感兴趣的文章
Qt 静态编译后的exe太大, 可以这样压缩.
查看>>
3D游戏常用技巧Normal Mapping (法线贴图)原理解析——基础篇
查看>>
C#的扩展方法解说
查看>>
.linearDrag on rigidbody / rigidbody2D in code?
查看>>
mute
查看>>
Google、微软软件测试之道
查看>>
Fiddler调试和Wireshark数据包分析
查看>>
Unity物品栏、商城3D物品的显示插件
查看>>
代码大全、人月神话和你的灯亮着吗三本软件开发设计方面好书
查看>>
Lua的闭包详解(终于搞懂了)
查看>>
Unity Standard Assets 简介之 CrossPlatformInput
查看>>
快速了解和使用Photon Server
查看>>
Unity之Application.runInBackground = true
查看>>
Unity之MVC 模式
查看>>
turret
查看>>
再谈AR中的图像识别算法
查看>>
开发增强现实(AR)教程——识别图的那些坑
查看>>
unity3d英语单词拼写小游戏Pics Quiz Maker With Categories 3.0
查看>>
unity填色绘画游戏Drawing Coloring Extra Edition
查看>>
unity缓动插件DOTween Pro v1.0.1
查看>>