热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

swift二进制读写_Swift二进制搜索树

swift二进制读写Inthistutorial,we’llbediscussingBinarytreesandtheimplementthevariousoperationsth

swift 二进制读写

In this tutorial, we’ll be discussing Binary trees and the implement the various operations that can be performed using it in Swift.

在本教程中,我们将讨论二叉树,并实现可在Swift中使用它执行的各种操作。

二进制搜索树 (Binary Search Tree)

A Binary Search Tree in Swift is a Binary Tree which must follow the following rules:

Swift中的Binary Search Tree是必须遵循以下规则的Binary Tree:


All node in the right subtree must have greater value than the value in the root node.
右子树中的所有节点的值必须大于根节点中的值。
Left and Right subtrees of root node should follow the above rules recursively.
根节点的左右子树应递归遵循上述规则。

They typically provide OLogN time for insertion and lookup.

它们通常为插入和查找提供OLogN时间。

Swift二进制搜索树实现 (Swift Binary Search Tree Implementation)

Let’s define the Node for a tree.

让我们为树定义节点。

class Node {var data: Tvar leftNode: Node?var rightNode: Node?init(data: T,leftNode: Node? = nil,rightNode: Node? = nil) {self.data = dataself.leftNode = leftNodeself.rightNode = rightNode}}

Let’s define the BinarySearchTree class in Swift. Here we’ll define functions to insert Nodes into the tree taking care of the BST rules:

让我们在Swift中定义BinarySearchTree类。 在这里,我们将定义一些函数,以将BST规则的节点插入树中:

class BST {private var rootNode: Node?func addNode(_ value: T) {let node = Node(data: value)if let rootNode = self.rootNode {self.insert(rootNode, node)} else {self.rootNode = node}}private func insert(_ root: Node, _ node: Node) {if root.data > node.data {if let leftNode = root.leftNode {self.insert(leftNode, node)} else {root.leftNode = node}} else {if let rightNode = root.rightNode {self.insert(rightNode, node)} else {root.rightNode = node}}}func printTree() {self.inorder(self.rootNode)}private func inorder(_ node: Node?) {guard let _ = node else { return }self.inorder(node?.leftNode)print("\(node!.data)", terminator: " ")self.inorder(node?.rightNode)}
}

We’ve assigned the Comparable and CustomStringConvertible protocols in order to compare the values of the Nodes and print the formatted data respectively.

我们已经分配了Comparable和CustomStringConvertible协议,以便比较Node的值并分别打印格式化的数据。

The inorder function prints the left subtree followed by the current node value, followed by right subtree

顺序函数打印左子树,后跟当前节点值,然后右子树

Now let’s add elements into the tree.

现在让我们将元素添加到树中。

let numberList : Array = [8, 2, 10, 9, 11, 1, 7]
var root = BST()
for number in numberList {root.addNode(number)
}
//should print sorted tree
root.printTree()

The output of the tree is:

swift binary search tree print

树的输出为:

As you can see the values in the BST are set in a sorted order.

如您所见,BST中的值是按排序顺序设置的。

在树中搜索值 (Searching a value in the tree)

extension BST {func search(value: T) {self.search(self.rootNode, value)}private func search(_ root: Node?, _ element: T) {guard let rootNode = root else {print("NODE is Not available : \(element)")return}print("current root node \(rootNode.data)")if element > rootNode.data {self.search(rootNode.rightNode, element)} else if element }

We’ve created a search function in the extension.
In this, we simply check the node value and based on the comparison, search it recursively in the left or right subtree.

我们在扩展程序中创建了搜索功能。
在此,我们只需检查节点值,然后根据比较结果,在左侧或右侧子树中递归搜索。

The output of two sample runs is:

两个示例运行的输出为:

删除节点 (Deleting a Node)

Implementation of Deleting a Node in a BST is a little more tricky.

在BST中删除节点的实现有些棘手。

After the node is deleted, we need to rearrange the BST so that it stays sorted.
Use the following rule for deletion:

删除节点后,我们需要重新排列BST,以使其保持排序状态。
使用以下规则进行删除:

After removing a node, we replace the node with either its biggest child on the left or its smallest child on the right subtree.
删除节点后,我们用左侧子树的最大子节点或右侧子树的最小子节点替换该节点。

This means we need to first create functions in our Node class for the minimum and maximum node of the tree.
The following illustration contains the updated class Node.

swift binary search tree node class

这意味着我们需要首先在Node类中为树的最小和最大节点创建函数。
下图包含更新的类Node。

And now we create another extension of the BST class for the deletion function which works recursively:

现在,我们为删除功能创建BST类的另一个扩展,该扩展递归地起作用:

extension BST{func deleteKey(value: T){rootNode &#61; deleteRec(rootNode, value)}/* A recursive function to insert a new key in BST */func deleteRec(_ root: Node?, _ key: T) -> Node?{/* Base Case: If the tree is empty */if root &#61;&#61; nil{return root}if key <(root?.data)! {root?.leftNode &#61; deleteRec(root?.leftNode, key)}else if key > (root?.data)!{root?.rightNode &#61; deleteRec(root?.rightNode, key)}else{if root?.leftNode &#61;&#61; nil{return root?.rightNode}else if root?.rightNode &#61;&#61; nil{return root?.leftNode}root?.data &#61; (minValue(root?.rightNode))!root?.rightNode &#61; deleteRec(root?.rightNode, (root?.data)!)}return root;}public func minValue(_ node: Node?) -> T? {var tempNode &#61; nodewhile let next &#61; tempNode?.leftNode {tempNode &#61; next}return tempNode?.data}}

The output when deleting the first key is:

swift binary search tree delete node

删除第一个键时的输出为&#xff1a;

That’s all for Swift Binary Search Tree implementation.

这就是Swift Binary Search Tree实现的全部内容。

翻译自: https://www.journaldev.com/21454/swift-binary-search-tree

swift 二进制读写



推荐阅读
  • Python正则表达式学习记录及常用方法
    本文记录了学习Python正则表达式的过程,介绍了re模块的常用方法re.search,并解释了rawstring的作用。正则表达式是一种方便检查字符串匹配模式的工具,通过本文的学习可以掌握Python中使用正则表达式的基本方法。 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • 阿里Treebased Deep Match(TDM) 学习笔记及技术发展回顾
    本文介绍了阿里Treebased Deep Match(TDM)的学习笔记,同时回顾了工业界技术发展的几代演进。从基于统计的启发式规则方法到基于内积模型的向量检索方法,再到引入复杂深度学习模型的下一代匹配技术。文章详细解释了基于统计的启发式规则方法和基于内积模型的向量检索方法的原理和应用,并介绍了TDM的背景和优势。最后,文章提到了向量距离和基于向量聚类的索引结构对于加速匹配效率的作用。本文对于理解TDM的学习过程和了解匹配技术的发展具有重要意义。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 如何使用Java获取服务器硬件信息和磁盘负载率
    本文介绍了使用Java编程语言获取服务器硬件信息和磁盘负载率的方法。首先在远程服务器上搭建一个支持服务端语言的HTTP服务,并获取服务器的磁盘信息,并将结果输出。然后在本地使用JS编写一个AJAX脚本,远程请求服务端的程序,得到结果并展示给用户。其中还介绍了如何提取硬盘序列号的方法。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • 不同优化算法的比较分析及实验验证
    本文介绍了神经网络优化中常用的优化方法,包括学习率调整和梯度估计修正,并通过实验验证了不同优化算法的效果。实验结果表明,Adam算法在综合考虑学习率调整和梯度估计修正方面表现较好。该研究对于优化神经网络的训练过程具有指导意义。 ... [详细]
  • 成功安装Sabayon Linux在thinkpad X60上的经验分享
    本文分享了作者在国庆期间在thinkpad X60上成功安装Sabayon Linux的经验。通过修改CHOST和执行emerge命令,作者顺利完成了安装过程。Sabayon Linux是一个基于Gentoo Linux的发行版,可以将电脑快速转变为一个功能强大的系统。除了作为一个live DVD使用外,Sabayon Linux还可以被安装在硬盘上,方便用户使用。 ... [详细]
  • 闭包一直是Java社区中争论不断的话题,很多语言都支持闭包这个语言特性,闭包定义了一个依赖于外部环境的自由变量的函数,这个函数能够访问外部环境的变量。本文以JavaScript的一个闭包为例,介绍了闭包的定义和特性。 ... [详细]
  • ALTERTABLE通过更改、添加、除去列和约束,或者通过启用或禁用约束和触发器来更改表的定义。语法ALTERTABLEtable{[ALTERCOLUMNcolu ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • 浏览器中的异常检测算法及其在深度学习中的应用
    本文介绍了在浏览器中进行异常检测的算法,包括统计学方法和机器学习方法,并探讨了异常检测在深度学习中的应用。异常检测在金融领域的信用卡欺诈、企业安全领域的非法入侵、IT运维中的设备维护时间点预测等方面具有广泛的应用。通过使用TensorFlow.js进行异常检测,可以实现对单变量和多变量异常的检测。统计学方法通过估计数据的分布概率来计算数据点的异常概率,而机器学习方法则通过训练数据来建立异常检测模型。 ... [详细]
author-avatar
Shelter-庇护所-Official
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有