二叉树 平衡二叉树 红黑树

In this tutorial, we’ll be discussing the Data Structure Trees and implement it using Swift. Furthermore, we’ll see what are Binary Trees and implement a few of its well-known algorithms.

在本教程中,我们将讨论数据结构树并使用Swift进行实现。 此外,我们将看到什么是二叉树并实现其一些众所周知的算法。

迅捷树 (Swift Trees)

Trees are a data structure that is just opposite to the real-life tree. The topmost node is called the root.

树是与真实树相反的数据结构。 最顶层的节点称为根。

Trees are a non-linear data structure, unlike Arrays. Trees structure have a hierarchy.

与数组不同,树是一种非线性数据结构。 树结构具有层次结构。

A node is a structure that holds data and also references to its child nodes.

节点是保存数据并引用其子节点的结构。

Root is the topmost node of the tree.

根是树的最高节点。

A node that doesn’t have any children is known as a leaf.

没有任何子节点的节点称为叶子

Trees are useful in sorting data, efficient searching, implementing routing table etc.

树在数据排序,有效搜索,实现路由表等方面很有用。

A diagram of a Tree is illustrated below:

树的图示如下所示:

The red box is the root node. The black boxes are nodes. The green boxes are the leaf of the tree.

红色框是根节点。 黑框是节点。 绿框是树的叶子。

  • Degree: is the total number of children in a node.程度 :是节点中子代的总数。
  • Siblings: Nodes that have the same parent.兄弟姐妹 :具有相同父节点的节点。
  • Edge: A Connection between two nodes.边缘 :两个节点之间的连接。

Let’s create a Tree data structure using Swift.

让我们使用Swift创建一个Tree数据结构。

Launch XCode playground and start rolling!

启动XCode游乐场并开始滚动!

创建迅捷树 (Creating Swift Tree)

The following swift class contains the code for the Node of a tree.

下面的swift类包含树节点的代码。

class Node<T>{var data: Tvar children: [Node] = []weak var parent: Node?init(_ data: T) {self.data = data}}

In the above code, we’ve set the data of the node in the init method.

在上面的代码中,我们已经在init方法中设置了节点的数据。

A Node can have any number of children. We’ve created an Array to add child nodes to the current node.

一个节点可以有任意数量的子代。 我们创建了一个数组来将子节点添加到当前节点。

Besides, we can set the reference to parent node as well. For this, we’ve set the reference to weak var to prevent strong cycles which can cause memory leaks.

此外,我们也可以设置对父节点的引用。 为此,我们将引用设置为weak var以防止可能导致内存泄漏的强循环。

Let’s instantiate the tree and add children.

让我们实例化树并添加子代。

let root = Node<Any>("Root")
let aNode = Node<Any>(1)
let bNode = Node<Any>(2)
let cNode = Node<Any>(3)
let dNode = Node<Any>("Anupam")
let eNode = Node<Any>("Swift")root.children = [aNode, bNode, cNode]
aNode.children = [dNode,cNode]
bNode.children = [dNode,eNode]
eNode.children = [Node("x"),Node("y"),Node(100)]

We’ve created a Generic type Tree, hence you need to state the type when defining.

我们已经创建了通用类型树,因此您需要在定义时声明类型。

So far so good. Next, how to print the tree?

到目前为止,一切都很好。 接下来,如何打印树?

Recursion is an important part of most operations on the data structure trees. Recursion is the key since every node is similar in structure – they either have children or they don’t.

递归是对数据结构树进行大多数操作的重要组成部分。 递归是关键,因为每个节点的结构都相似-它们要么有子节点,要么没有子节点。

Hence, to perform any operation you need to invoke the method on the node’s children. The trivial condition would be when there’s just a single node (root node). That’s where you do the operation.

因此,要执行任何操作,您需要在节点的子节点上调用方法。 琐碎的条件是只有一个节点(根节点)时。 那是您进行操作的地方。

Add the following function in the class Node

class Node添加以下函数

func printNodeData() -> [String] {return ["\(self.data)"] + self.children.flatMap{$0.printNodeData()}.map{"    "+$0}}func printTree() {let text = printNodeData().joined(separator: "\n")print(text)}

In this we need to convert the data to a string since the type is generic. So we enclose it in "\()".

由于类型是通用的,因此我们需要将数据转换为字符串。 因此,我们将其包含在"\()"

在树中添加和搜索 (Adding and Searching in a Tree)

In the above code, we’ve added nodes to the parent in a hardcoded way. Let’s create a function for it.

在上面的代码中,我们以硬编码方式将节点添加到了父节点。 让我们为其创建一个函数。

Furthermore, let’s create a function for searching an element in the tree.

此外,让我们创建一个用于搜索树中元素的函数。

Add the following functions in the node class.

在节点类中添加以下功能。

func addNode(child: Node){children.append(child)child.parent = self}func search(element: T) -> Node?{if "\(element)" == "\(self.data)"{return self}for child in children{if let result = child.search(element: element){return result}}return nil}

Let’s build a small tree and print it in the console.

让我们构建一棵小树并在控制台中将其打印出来。

树木类型 (Types of Trees)

Following are the different kinds of trees:

以下是不同种类的树:

  • Binary Tree二叉树
  • AVL TreeAVL树
  • Binary Search Tree二进制搜索树
  • B-TreeB树
  • Minimum Spanning Tree最小生成树
  • Radix Tree板蓝树
  • Red-Black Tree红黑树
  • Segment Tree段树
  • Threaded Binary Tree线程二叉树
  • Tries尝试
  • Union-Find联合发现

We’ll cover each of these later. In the next section, we’ll be discussing Binary Trees.

我们稍后将介绍这些内容。 在下一节中,我们将讨论二叉树。

二叉树 (Binary Trees)

Binary trees are data structures in which a node can have only 0, 1 or 2 children.

二进制树是一种数据结构,其中一个节点只能有0、1或2个子节点。

The following class is used to create a Binary Tree.

下列类用于创建二叉树。

class TreeNode {var value: Intvar leftChild: TreeNode?var rightChild: TreeNode?init(_ value: Int,_ leftChild: TreeNode?,_ rightChild: TreeNode?) {self.value = valueself.rightChild = rightChildself.leftChild = leftChild}
}

Let’s build it by adding nodes and child nodes.

让我们通过添加节点和子节点来构建它。

let ten = TreeNode(10,nil,nil)
let one = TreeNode(0,nil,nil)
let third = TreeNode(3,nil,nil)
let fourth = TreeNode(4,nil,nil)
let five = TreeNode(5,ten,third)
let six = TreeNode(6,fourth,nil)
let root = TreeNode(2,five,six)

Following is how the tree looks like:

以下是树的外观:

二叉树的高度 (Height of Binary tree)

The depth of a node is the number of edges from the node to the tree’s root node.
A root node will have a depth of 0.

节点深度是从节点到树的根节点的边数。
根节点的深度为0。

The height of a node is the number of edges on the longest path from the node to a leaf.
A leaf node will have a height of 0.

节点高度是从节点到叶子的最长路径上的边数。
叶节点的高度为0。

Height of a tree begins at the root node and is equal to the depth of the farthest leaf. The leaf with the longest path.

一棵树的高度从根节点开始,等于最远的叶子的深度。 路径最长的叶子。

Add the following function in the TreeNode class.

在TreeNode类中添加以下函数。

func maxDepth(_ root: TreeNode?) -> Int{if root == nil{return 0}else{let lDepth = maxDepth(root?.leftChild);let rDepth = maxDepth(root?.rightChild);if (lDepth > rDepth){return(lDepth+1)}else {return(rDepth+1)}}}

To get the height of the tree, invoke the function on an instance of TreeNode and pass the root.

要获取树的高度,请在TreeNode实例上调用该函数并传递根。

let t = TreeNode(0,nil,nil)
t.maxDepth(root) //3

二叉树遍历 (Binary Tree Tranversals)

We can traverse the tree in three possible ways:

我们可以通过三种可能的方式遍历树:

  1. Inorder – Prints the left child value then current node value and lastly right child value.顺序 –打印左子值,然后打印当前节点值,最后打印右子值。
  2. Postorder – Prints left and right child values then current node value.后订购 –打印左右子值,然后打印当前节点值。
  3. Preorder – Prints current node value followed by left and right child values.预排序 –打印当前节点值,然后打印左右子值。

Let’s write a function for each of them in the TreeNode class.

让我们在TreeNode类中为每个函数编写一个函数。

func inorderTraversal(_ root: TreeNode?) -> [Int] {if root == nil {return []}var result: [Int] = []result += inorderTraversal(root!.leftChild)result.append(root!.value)result += inorderTraversal(root!.rightChild)return result}

We recursively call the leftmost subtree followed by printing the node value and then calling the rightmost subtree.

我们递归地调用最左边的子树,然后打印节点值,然后调用最右边的子树。

Preorder:

预购

func preorderTraversal(_ root: TreeNode?) -> [Int] {if root == nil {return []}var result: [Int] = []result.append(root!.value)result += preorderTraversal(root!.leftChild)result += preorderTraversal(root!.rightChild)return result}

Postorder:

邮购

func postorderTraversal(_ root: TreeNode?) -> [Int] {if root == nil {return []}var result: [Int] = []result += postorderTraversal(root!.leftChild)result += postorderTraversal(root!.rightChild)result.append(root!.value)return result}

The output is given below:

输出如下:

This brings an end to this tutorial on Trees and Binary Trees in Swift.

这样就结束了有关Swift中的树和二叉树的本教程。

翻译自: https://www.journaldev.com/21383/swift-tree-binary-tree-data-structure

二叉树 平衡二叉树 红黑树

二叉树 平衡二叉树 红黑树_迅捷树,二叉树相关推荐

  1. java 二叉树 红黑树_常见数据结构(二)-树(二叉树,红黑树,B树)

    常见数据结构(二)-树(二叉树,红黑树,B树) 标签: algorithms [TOC] 本文介绍数据结构中几种常见的树:二分查找树,2-3树,红黑树,B树 写在前面 本文所有图片均截图自course ...

  2. 【Mysql索引】二叉树、红黑树、B树、B+树

    [Mysql索引]二叉树.红黑树.B树.B+树 (1)哈希表 (2)二叉树的弊端的演示: (3)红黑树的插入演示: (4)B树的演示 (5)B+树的演示(叶子加指针:支持范围查找) (5.1)借着学习 ...

  3. 算法笔记(二叉树、红黑树、b+树等)

    文章目录 不同数据库用的什么索引,什么树结构 一张表可以有几个聚集索引 oracle用的是聚集索引吗 不是 oracle用的都是非聚集索引 oracle为什么不用聚集索引 InnoDB一棵B+树可以存 ...

  4. 二叉树、红黑树、B树、B+树、图、Trie树合集-----妈妈再也不用担心我的“树”拉!

    这里把各种树做个总结,分别介绍各个树是什么,什么原理,什么特点,什么情况下使用,另外很多时候它们很多地方是相似的,还要加以区别,之前我身边一个很多年开发的经验的老开发还以为B树.B-树.B+树是三种树 ...

  5. 数据结构树、二叉树、完全二叉树、二叉查找树、平衡二叉树、红黑树、B+树

    树.二叉树.平衡二叉树.二叉搜索树 树的前序遍历.中序遍历和后序遍历 树的前序遍历.中序遍历和后续遍历是以遍历时根所在的位置顺序命名的.层次遍历即按层从上至下,从左至右遍历即可. 前序遍历:根-> ...

  6. 总结下各种常见树形结构的定义及特点(二叉树、AVL树、红黑树、Trie树、B树、B+树)

    文章目录 前言 一棵普通的树 相关术语 二叉树 二叉树性质 二叉树特例 二叉查找树 AVL树 特点及应用 红黑树 特点 应用 Trie树 特点及应用 B树 定义及特点 应用 B+树 B+树的优势及应用 ...

  7. 二叉树、红黑树 、平衡二叉树

    二叉搜索树的概念 二叉搜索树又称为二叉排序树,它或者是一棵空树,或者是具有以下性质的二叉树: 若它的左子树不为空,则左子树上所有结点的值都小于根结点的值. 若它的右子树不为空,则右子树上所有结点的值都 ...

  8. 算法笔记:二叉树,红黑树

    目录 <树>知识点: 二叉查找,搜索,排序树BST: 平衡二叉树:AVL树: 平衡二叉树的目的: 平衡二叉树的常用方法: 红黑树:RB Tree 红黑树性质: 旋转和颜色变化的规律: 红黑 ...

  9. 数据结构找你妹(一)从二叉树到红黑树的分析实现

    什么是查找? 好了,我们今天的主题是--找你妹.或许应该把话题提升到一个不那么"好听"的层次--查找.但还是从"好听"的讲起吧,我们应该都玩过"找你妹 ...

最新文章

  1. QTableWidget控件总结
  2. 用Xamarin 实现园友的 :Android浮动小球与开机自启动
  3. cad蜂鸟工具_蜂鸟视图地图数据中台,全面提升商业地产的可视化信息管控
  4. 【第四周作业】参加项目开发之后的一些体会
  5. Java集合 Collection
  6. Linux下rc.local不执行问题
  7. 计算机蓝屏分析报告,如何获取电脑蓝屏后的错误报告DMP文件
  8. 博微JAVA面试_博微Java笔试题
  9. World中利用宏命令批量删除页眉和页脚
  10. 35年老程序员个人谈:C语言时代行将落幕
  11. 本地启动本地mysql_通过本地化启动并运行
  12. 基于Web实现在线绘画拓扑图[GraphEditor]
  13. java 括号匹配_Java解决括号匹配算法问题
  14. iOS-百度地图之——POI检索失败BMK_SEARCH_PERMISSION_UNFINISHED
  15. 室内定位技术之UWB篇
  16. 一文搞懂CAN FD总线
  17. pdf 转 word 支持各种格式【在线办公工具】
  18. 2022渗透测试-文件上传漏洞的详细讲解
  19. 学习python的难点
  20. 国际法学19春在线作业1-0005

热门文章

  1. .NET之我见系列 - 类型系统(上)
  2. [转载] Golang-简洁的并发
  3. HDFS中的集中缓存管理详解
  4. Windows下基于python3使用word2vec训练中文维基百科语料(三)
  5. 定制geojson的一些小技巧和方法
  6. android——数据库版本升/降级问题
  7. Java阻塞队列的实现
  8. iOS限制文本输入长度进阶之 一
  9. UVALive - 3641 Leonardo's Notebook(polya计数)
  10. Delphi的Hint(2)