binary tree in golang
// Binary Tree in Golang
package main
import (
"fmt"
"os"
"io"
)
type BinaryNode struct {
left *BinaryNode
right *BinaryNode
data int64
}
type BinaryTree struct {
root *BinaryNode
}
func (t *BinaryTree) insert(data int64) *BinaryTree {
if t.root == nil {
t.root = &BinaryNode{data: data, left: nil, right: nil}
} else {
t.root.insert(data)
}
return t
}
func (n *BinaryNode) insert(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.insert(data)
}
} else {
if n.right == nil {
n.right = &BinaryNode{data: data, left: nil, right: nil}
} else {
n.right.insert(data)
}
}
}
func print(w io.Writer, node *BinaryNode, ns int, ch rune) {
if node == nil {
return
}
for i := 0; i < ns; i++ {
fmt.Fprint(w, " ")
}
fmt.Fprintf(w, "%c:%v\n", ch, node.data)
print(w, node.left, ns+2, 'L')
print(w, node.right, ns+2, 'R')
}
func main() {
tree := &BinaryTree{}
tree.insert(100).
insert(-20).
insert(-50).
insert(-15).
insert(-60).
insert(50).
insert(60).
insert(55).
insert(85).
insert(15).
insert(5).
insert(-10)
print(os.Stdout, tree.root, 0, 'M')
}
Are there any code examples left?
New code examples in category Go
-
Go 2022-03-27 22:30:23 golang check if ip is v6
-
Go 2022-03-27 16:20:18 make image go to center of page
-
Go 2022-03-24 15:20:01 why does my discord bot not work when i take code from googl
-
Go 2022-03-21 18:40:22 pass method as props vue
-
Go 2022-03-19 23:40:33 reverse a string in golang
-
Go 2022-03-18 12:45:06 golang while loop
-
Go 2022-03-17 19:30:08 instancing in godot
-
Go 2022-03-17 09:55:17 brew upgrae golang-migrate
-
Go 2022-03-17 06:15:06 Tushar Jadhav
-
Go 2022-03-17 00:00:12 golang cwd