Browse Source

Adding binary tree in Go

master
Charles Reid 5 years ago
parent
commit
2603def0bd
  1. 68
      go/BinaryTree.go
  2. 18
      go/LinkedList.go

68
go/BinaryTree.go

@ -0,0 +1,68 @@
package main
import "fmt"
//////////////////////////////////////////
// Binary Tree Node
// Define a binary tree node.
// Each node has data,
// and each node has a left and right.
type Node struct {
data int32
left *Node
right *Node
}
// Function defined for Nodes, that turns them into Strings
func (n *Node) String() string {
return fmt.Sprintf("Node: %d", n.data)
}
func (n *Node) print() {
fmt.Println(n.data)
if n.left!=nil {
n.left.print()
}
if n.right!=nil {
n.right.print()
}
}
//////////////////////////////////////////
// Binary Tree
// Define a binary tree.
type BinaryTree struct{
root *Node
}
////////////////////////////////////////
// Test
func main() {
bt := new(BinaryTree)
root := new(Node)
root.data = 5
root.left = new(Node)
root.right = new(Node)
root.left.data = 15
root.right.data = 23
root.left.left = new(Node)
root.left.right = new(Node)
root.left.left.data = 25
root.left.right.data = 38
root.right.left = new(Node)
root.right.right = new(Node)
root.right.left.data = 27
root.right.right.data = 44
bt.root = root
bt.root.print()
}

18
go/LinkedList.go

@ -1,3 +1,6 @@
////////////////////////////////////////////////
// Linked List Node
// Start by defining a node.
// The data type is interface{}, which means we can define a type as a struct, just like we do here, and pass it as a data type.
// A linked list node is a burrito for data.
@ -6,10 +9,12 @@ type Node struct {
next *Node
}
// Define an Append function for the Node struct.
// This appends some data to the linked list, right after node n (not at the end).
// Defined for this type
// \/\/\/
// Returns this type
// \/\/\/
func ( n *Node ) Append(data interface{}) *Node {
// If we are on the last node at the end of the list:
@ -33,3 +38,12 @@ func ( n *Node ) Append(data interface{}) *Node {
func (n *Node) String() string {
return fmt.Sprintf("Node: %v", n.data)
}
////////////////////////////////////////////////
// Linked List
type LinkedList struct {
root Node*
}

Loading…
Cancel
Save