Ex_GoAlgorithms/binaryTreeInsertPrint.go

62 lines
976 B
Go
Raw Normal View History

2024-05-30 11:50:30 +04:00
package main
import "fmt"
type BinaryNode struct {
Key int
Left *BinaryNode
Right *BinaryNode
}
type BinaryTree struct {
Root *BinaryNode
}
// Insert will add a node to the tree
func (t *BinaryTree) Insert(key int) {
if t.Root == nil {
t.Root = &BinaryNode{Key: key}
} else {
t.Root.Insert(key)
}
}
// Insert a node
func (n *BinaryNode) Insert(key int) {
if n.Key < key {
// move right
if n.Right == nil {
n.Right = &BinaryNode{Key: key}
} else {
n.Right.Insert(key)
}
} else if n.Key > key {
// move left
if n.Left == nil {
n.Left = &BinaryNode{Key: key}
} else {
n.Left.Insert(key)
}
}
}
// InOrderPrint prints the tree in order
func (t *BinaryTree) InOrderPrint() {
if t.Root != nil {
t.Root.InOrderPrint()
}
}
// InOrderPrint returns the tree in order
func (n *BinaryNode) InOrderPrint() {
if n.Left != nil {
n.Left.InOrderPrint()
}
fmt.Printf("%v ", n.Key)
if n.Right != nil {
n.Right.InOrderPrint()
}
}