二叉树 平衡二叉树 红黑树_迅捷树,二叉树

二叉树 平衡二叉树 红黑树

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: T
    var 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 Tree

    AVL树
  • Binary Search Tree

    二进制搜索树
  • B-Tree

    B树
  • 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: Int
    var leftChild: TreeNode?
    var rightChild: TreeNode?
    
    init(_ value: Int,_ leftChild: TreeNode?,_ rightChild: TreeNode?) {
        self.value = value
        self.rightChild = rightChild
        self.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:

swift binary tree example

以下是树的外观:

二叉树的高度 (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:

swift binary tree example traversals

输出如下:

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

二叉树 平衡二叉树 红黑树

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值