Trees
BST Search
Search a binary search tree for one present and one absent value.
Algorithm
Basic Implementation
basic.go
package main
import (
"fmt"
"strings"
)
type Node struct { value int; left *Node; right *Node }
func render(node *Node) string {
if node == nil { return "_" }
if node.left == nil && node.right == nil { return fmt.Sprintf("%d", node.value) }
return fmt.Sprintf("%d(%s,%s)", node.value, render(node.left), render(node.right))
}
func sampleTree() *Node {
return &Node{4, &Node{2, &Node{1, nil, nil}, &Node{3, nil, nil}}, &Node{6, &Node{5, nil, nil}, &Node{7, nil, nil}}}
}
func listString(values []int) string {
parts := []string{}
for _, value := range values { parts = append(parts, fmt.Sprintf("%d", value)) }
return "[" + strings.Join(parts, ", ") + "]"
}
func search(root *Node, target int) bool { node := root; for node != nil { if target == node.value { return true }; if target < node.value { node = node.left } else { node = node.right } }; return false }
func main() { root := sampleTree(); if search(root, 5) { fmt.Println("5 found") } else { fmt.Println("5 not found") }; if search(root, 8) { fmt.Println("8 found") } else { fmt.Println("8 not found") } }
Complexity
- Time: O(h) per search
- Space: O(1) iterative
Implementation notes
- Go uses
type Node struct { value int; left *Node; right *Node }; the sample tree is built from*Nodepointers withnilchild links. search(root *Node, target int) boolis iterative. It copiesrootinto a localnodecursor, reads pointers, and never mutates the tree.- The loop condition
for node != nilguards eachnode.valueread. On equality the function returnstrue; otherwisetarget < node.valuemoves tonode.left, and theelsebranch moves tonode.right. - The trace starts from
4(2(1,3),6(5,7)). Searching5visits cursor4and branches right, visits6and branches left, then matches at5. - Searching
8visits4,6, and7, branches right each time, then reaches a nil cursor and returnsfalse. This lesson has no separate imbalance or degradation contrast; the checked trace only shows the balanced-tree miss path. mainformats results with string literals around the boolean return:fmt.Println("5 found")andfmt.Println("8 not found"), producing the two-line output5 found/8 not found.
search path
A comparison chooses one subtree at each step, so whole branches are skipped.