Build trees and heaps
Build trees and heaps
A binary search tree maintains smaller keys in the left subtree and larger keys in the right subtree (choose a duplicate policy). A min-heap instead maintains each parent no larger than its children. The tree supports ordered search; the heap exposes the minimum efficiently without fully sorting all keys.
package main
import ( "fmt")
type Tree struct { key int left, right *Tree}
func insert(t *Tree, k int) *Tree { if t == nil { return &Tree{key: k} } if k < t.key { t.left = insert(t.left, k) } else if k > t.key { t.right = insert(t.right, k) } return t}func ordered(t *Tree, out *[]int) { if t == nil { return } ordered(t.left, out) *out = append(*out, t.key) ordered(t.right, out)}func main() { var t *Tree for _, k := range []int{5, 2, 8, 2, 4} { t = insert(t, k) } var out []int ordered(t, &out) fmt.Println(out)}Equal keys are ignored. In-order traversal visits left, root, right, producing sorted distinct keys. Insert costs O(h) for height h; an unbalanced tree can have h=n. This example does not rebalance. Recursive traversal uses O(h) call stack space.
Expected output:
[2 4 5 8]Use a min-heap priority queue
package main
import ( "container/heap" "fmt")
type IntHeap []int
func (h IntHeap) Len() int { return len(h) }func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] }func (h *IntHeap) Push(x any) { *h = append(*h, x.(int)) }func (h *IntHeap) Pop() any { a := *h; i := len(a) - 1; v := a[i]; *h = a[:i]; return v }func main() { h := IntHeap{5, 1, 7} heap.Init(&h) heap.Push(&h, 2) for h.Len() > 0 { fmt.Println(heap.Pop(&h)) }}container/heap uses Len, Less and Swap plus Push and Pop hooks. Call heap.Push and heap.Pop, not the hooks directly, so the package restores the invariant. The Pop hook removes the last element after the package moves the minimum there. Init is O(n); push and pop O(log n). Check length before popping. This int-only heap assumes callers supply int values.
Expected output:
1257Try it locally
Write contains(t *Tree,k int) bool for a binary search tree. Construct a tree with root 4 and children 2 and 6; check 6 and 5.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Data structures 04: Build trees and heaps
Check the lesson objective before moving on.
What is guaranteed by a min-heap invariant?
What is the worst-case height of an unbalanced n-node search tree?