Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Data Structures in Go: Tree (BST)
Dorin
Dorin

Posted on • Originally published atfodor.org

     

Data Structures in Go: Tree (BST)

Introduction

ATree is a non-linear data structure which consists of one or more nodes where a node can have zero or more references to other nodes which will form a sub-tree.

Alt Text

There are multiple types of trees: ordered, un-ordered, balanced, non-balanced, with two children, with more than two children, etc.

For the purpose of this article I have chosen to implement a non-balancedBinary Search Tree, which is an ordered tree with two child nodes. The one on the left will always contain a smaller value and the one on the right a greater value.

Implementation

To start with, we are going to create a struct which is going to represent a single node of our tree. There will always be a node at the top, to which everything else is going to be added.

// Node : represents a single node of a Tree data structuretypeNodestruct{Left*NodeRight*NodeDataint}
Enter fullscreen modeExit fullscreen mode

Next we add a constructor functionNew which will take the value of the first node and return an instance of a tree node.

// New : constructor function for a Tree nodefuncNew(dataint)*Node{return&Node{Left:nil,Right:nil,Data:data,}}
Enter fullscreen modeExit fullscreen mode

Now we are going to add a few methods to our tree node struct. These are going to be:Insert,Contains andTraverse.

TheInsert method is going to add a node with the value passed to it, to the tree. We are going to recursively look into all the nodes until we find a suitable location with anil reference where we can append the new node.

// Insert : adds a node to the treefunc(t*Node)Insert(dataint)*Node{ifdata<t.Data{ift.Left!=nil{t.Left.Insert(data)}else{t.Left=New(data)}}else{ift.Right!=nil{t.Right.Insert(data)}else{t.Right=New(data)}}returnt}
Enter fullscreen modeExit fullscreen mode

Then we add theContains method which is going to start traversing the tree and look for a node with a specific value. It will return a boolean with the success status.

// Contains : checks if the tree contains a node with a given valuefunc(t*Node)Contains(dataint)bool{ift.Data==data{returntrue}ifdata<t.Data{ift.Left!=nil{t.Left.Contains(data)}else{returnfalse}}else{ift.Right!=nil{t.Right.Contains(data)}else{returnfalse}}returnfalse}
Enter fullscreen modeExit fullscreen mode

And lastly we add theTraverse method which is going to traverse the entirety of the tree and print all its values to the standard output.

// Traverse : prints all elements of the treefunc(t*Node)Traverse(){ift.Left!=nil{t.Left.Traverse()}fmt.Println(t.Data)ift.Right!=nil{t.Right.Traverse()}}
Enter fullscreen modeExit fullscreen mode

Conclusion

We ended up with a basic Binary Search Tree which will let us add any element to it with a complexity of O(n) and search, in the worst case also with O(n). This is not ideal and it is possible to improve the tree by making sure it is balanced. A balanced tree would let us search at O(log(n)).

Stay tuned for new posts on how to balance our tree!

Source code with tests

GitHub logo dorin131 / go-data-structures

A collection of data structures implemented in Go

Video

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Software engineer passionate about JavaScript, TypeScript, WebAssembly, Go and curious about DevOps.
  • Location
    London, UK
  • Joined

More fromDorin

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp