Go
Official website
The official website for the Go programming language is https://golang.org.
Static typing
Yes, Go is a statically typed language. This means that the type of every variable is known at compile time, which helps catch type errors before the code runs. While Go does have mechanisms like type inference (using the := syntax) that can automatically deduce types, the language is still fundamentally statically typed.
Example code
Below is a complete Go program that defines a binary search tree, inserts values into it, and includes a function to find a value in the tree:
package main
import (
"fmt"
)
// TreeNode is a node in a binary search tree.
type TreeNode struct {
Value int
Left *TreeNode
Right *TreeNode
}
// Insert inserts a new value into the BST.
func (node *TreeNode) Insert(value int) {
if value < node.Value {
// Insert in the left subtree.
if node.Left == nil {
node.Left = &TreeNode{Value: value}
} else {
node.Left.Insert(value)
}
} else if value > node.Value {
// Insert in the right subtree.
if node.Right == nil {
node.Right = &TreeNode{Value: value}
} else {
node.Right.Insert(value)
}
}
// If value == node.Value, we'll do nothing to avoid duplicates.
}
// Find searches for a value in the binary search tree.
// It returns a pointer to the TreeNode if found, or nil if the value is not present.
func (node *TreeNode) Find(value int) *TreeNode {
if node == nil {
return nil
}
if value == node.Value {
return node
} else if value < node.Value {
return node.Left.Find(value)
} else {
return node.Right.Find(value)
}
}
func main() {
// Create the BST with an initial root node.
root := &TreeNode{Value: 50}
// Insert some values.
values := []int{30, 70, 20, 40, 60, 80}
for _, v := range values {
root.Insert(v)
}
// Value to search for.
target := 60
result := root.Find(target)
if result != nil {
fmt.Printf("Found node with value: %d\n", result.Value)
} else {
fmt.Printf("Value %d not found in the tree.\n", target)
}
}
Explanation
-
TreeNode Structure:
TheTreeNodestruct has an integerValueand pointers to the left and right children. -
Insert Function:
TheInsertmethod recursively places a new integer into the binary search tree according to BST rules (left child is less than the parent, right child is greater than the parent). - Find Function:
TheFindmethod searches the tree recursively:- If the current node is
nil, the search terminates and returnsnil. - If the searched value equals the node’s value, the node is returned.
- Otherwise, the search continues in the left or right subtree depending on the value.
- If the current node is
- main Function:
In themainfunction, a tree is created, populated with several values, and then a search is performed for a specific target value. The result is printed to the console.
This implementation is a simple demonstration of binary search tree operations in Go.