Skip to content

Commit

Permalink
feat: implementation binary tree
Browse files Browse the repository at this point in the history
  • Loading branch information
rulanugrh committed Mar 11, 2024
1 parent 2f01ecb commit ee3f933
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
11 changes: 10 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
package main

import (
"os"

"github.com/rulanugrh/veletudo/tree"
)

func main() {
println("Hello World")
t := &tree.BinaryTree{}
t.InsertData(100).InsertData(-20).InsertData(-50).InsertData(-15).InsertData(-60).InsertData(50).InsertData(60).InsertData(55).InsertData(75).InsertData(15).InsertData(5).InsertData(-10)

tree.Printout(os.Stdout, t.Root, 0, 'M')
}
58 changes: 58 additions & 0 deletions tree/bsts.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package tree

import (
"fmt"
"io"
)

type BinaryNode struct {
left *BinaryNode
right *BinaryNode
data int64
}

type BinaryTree struct {
Root *BinaryNode
}

func (t *BinaryTree) InsertData(data int64) *BinaryTree {
if t.Root == nil {
t.Root = &BinaryNode{data: data, left: nil, right: nil}
} else {
t.Root.InsertNode(data)
}

return t
}

func (n *BinaryNode) InsertNode(data int64) {
if n == nil {
return
} else if data <= n.data {
if n.left == nil {
n.left = &BinaryNode{data: data, left: nil, right: nil}
} else {
n.left.InsertNode(data)
}
} else {
if n.right == nil {
n.right = &BinaryNode{data: data, left: nil, right: nil}
} else {
n.right.InsertNode(data)
}
}
}

func Printout(w io.Writer, node *BinaryNode, ns int, ch rune) {
if node == nil {
return
}

for i := 0; i < ns; i++ {
fmt.Fprintf(w, " ")
}

fmt.Fprintf(w, "%c:%v\n", ch, node.data)
Printout(w, node.left, ns+2, 'L')
Printout(w, node.right, ns+2, 'R')
}

0 comments on commit ee3f933

Please sign in to comment.