Implement Tree with Swift

Implement Tree with Swift

Let’s start it with the definition of tree. What is Tree in programming? Tree is a data structure that contains a hierarchical relation between its elements. Tree has so many types, but in this topic, we only talk about Tree in general. For other types, we will talk about it in a specific topic later.

No alt text provided for this image

We can see that the node is an element that has branch/es that connected with other elements. The leaf is an element that doesn’t have any branch. The root is the highest level hierarchy node.

And now let’s code it.

class Node<ValueType: Equatable> {
    weak var parent: TreeNode?
    var data: ValueType
    var children: [TreeNode] = []
    
    init(data: ValueType) {
        self.data = data
    }
}

Each node will contain parent, data, and childer (array of nodes that become the children). For the parent variable, we set it as a weak variable to avoid the `memory cycle problem`. If you don't understand it, you can read about Automatic Reference Counting (ARC).

For now, we only make 2 methods in this function, those are `add(child:)` and `search(element:)`.

class TreeNode<ValueType: Equatable> {
    weak var parent: TreeNode?
    var data: ValueType
    var children: [TreeNode] = []
    
    init(data: ValueType) {
        self.data = data
    }
    
    func add(child: TreeNode) {
        child.parent = self
        children.append(child)
    }
    
    func search(element: ValueType) -> TreeNode? {
        if element == data {
            return self
        }
        
        for child in children {
            if let result = child.search(element: element) {
                return result
            }
        }
        
        return nil
    }
}

And we need a method to print the hierarchy in the TreeNode to see does our code run properly or not. Here’s the implementation for the print the TreeNode Hierarchy:

func printTreeHierarchy() {
    print(getNodeHierarchy().joined(separator: "\n"))
}
private func getNodeHierarchy(level: Int = 0) -> [String] {
    var spacing: String = ""
    
    for _ in 0..<level {
        spacing += "\t"
    }
    
    var results: [String] = [spacing + "\(data)"]
    
    for child in children {
        results += child.getNodeHierarchy(level: level + 1)
    }
    
    return results
}

Now, we’ll make implementation for a tree like this:

No alt text provided for this image

Here’s the code:

let techTeam: TreeNode<String> = TreeNode<String>(data: "Technology Team")
let frontEndTeam: TreeNode<String> = TreeNode<String>(data: "Front End Team")

techTeam.add(child: frontEndTeam)
techTeam.add(child: TreeNode<String>(data: "Back End Team"))
techTeam.add(child: TreeNode<String>(data: "Data Team"))

frontEndTeam.add(child: TreeNode<String>(data: "iOS Team"))
frontEndTeam.add(child: TreeNode<String>(data: "Android Team"))
frontEndTeam.add(child: TreeNode<String>(data: "Web Team"))

techTeam.printTreeHierarchy()

And the result will be:

Technology Team
    Front End Team
        iOS Team
        Android Team
        Web Team
    Back End Team
    Data Team

So, here’s the explanation about the basics of Tree. We will talk about other types of trees in another specific topic.



要查看或添加评论,请登录

David Jourdan Manalu的更多文章

  • Implement MVVM on ReactJS (Using TypeScript)

    Implement MVVM on ReactJS (Using TypeScript)

    MVVM is a design pattern that is very often used by Front-End Engineers. The main idea of this design pattern is to…

  • Write Simple Get Method on Vapor 4 (with Swift)

    Write Simple Get Method on Vapor 4 (with Swift)

    Okay, so this article is the continuation from `Start Using Vapor (with Swift)`. In this article, I will show a simple…

    1 条评论
  • Start Using Vapor 4 (with Swift)

    Start Using Vapor 4 (with Swift)

    So today I want to share my experience when make Server-Side Project using Vapor with Swift. We will start with a very…

  • Linked Lists with SWIFT

    Linked Lists with SWIFT

    General Definition for LinkedList What is a linked list? A linked list is a data structure that holds a group of nodes…

社区洞察

其他会员也浏览了