
A Binary Search Tree (BST) is a foundational concept and forms the basis for understanding more complex tree-based data structures. They are widely used for their simplicity and efficiency in operations to insert, delete & search.
- Each node has at most 2 children.
- The left child's value is less than its parent's value.
- The right child's value is greater than its parent's value.
However, we can have an issue with the time complexity of the underlying algorithm where the height of the tree can become imbalanced, leading to degraded performance. To tackle this, we can opt to use self-balancing tree structures like B-trees, B+trees, etc.
BST Implementation in Go
package main
import (
"fmt"
)
type Node struct {
value int
left *Node
right *Node
}
func insert(root *Node, value int) *Node {
if root == nil {
return &Node{value: value}
}
if value < root.value {
root.left = insert(root.left, value)
} else if value > root.value {
root.right = insert(root.right, value)
}
return root
}
func inorder(root *Node) {
if root != nil {
inorder(root.left)
fmt.Print(root.value, " ")
inorder(root.right)
}
}
func main() {
var root *Node
values := []int{50, 30, 20, 40, 70, 60, 80}
for _, v := range values {
root = insert(root, v)
}
fmt.Print("Inorder traversal: ")
inorder(root)
}
Explanation
- Node struct: Represents a node in the BST with a value and pointers to left and right children.
- insert: Recursively inserts a value into the BST.
- inorder: Performs an inorder traversal (left, root, right) to print the BST in sorted order.
- main: Demonstrates creating a BST and printing its inorder traversal.
This is a basic implementation. In production, you may want to add methods for deletion, searching, and balancing the tree.