From ee3f933f779473fe2a531595675739acf865fd27 Mon Sep 17 00:00:00 2001 From: rulanugrh Date: Mon, 11 Mar 2024 16:21:13 +0700 Subject: [PATCH] feat: implementation binary tree --- main.go | 11 +++++++++- tree/bsts.go | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 tree/bsts.go diff --git a/main.go b/main.go index 010d0a3..ce1de8d 100644 --- a/main.go +++ b/main.go @@ -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') } diff --git a/tree/bsts.go b/tree/bsts.go new file mode 100644 index 0000000..c4bf81a --- /dev/null +++ b/tree/bsts.go @@ -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') +}