Bird
Raised Fist0
DSA Goprogramming

BST Property and Why It Matters in DSA Go

Choose your learning style10 modes available
Mental Model
A Binary Search Tree keeps smaller values on the left and bigger values on the right, making searching fast.
Analogy: Imagine a library where books are arranged so that all books with titles starting with letters before 'M' are on the left shelves, and those after 'M' are on the right shelves. This helps you find a book quickly without checking every shelf.
       10
      /  \
     5    15
    / \     \
   3   7     20
Dry Run Walkthrough
Input: BST with nodes 10, 5, 15, 3, 7, 20; search for value 7
Goal: Show how BST property helps find 7 quickly by deciding left or right at each step
Step 1: Start at root node 10
       [10↑]
      /    \
     5      15
    / \       \
   3   7       20
Why: We begin search at the root to compare the target value
Step 2: Compare 7 with 10; 7 is less, go left to node 5
       10
      /    \
    [5↑]    15
    / \       \
   3   7       20
Why: BST property says smaller values are on the left, so we go left
Step 3: Compare 7 with 5; 7 is greater, go right to node 7
       10
      /    \
     5      15
    /   \     \
   3   [7↑]    20
Why: BST property says bigger values are on the right, so we go right
Step 4: Found node 7, stop search
       10
      /    \
     5      15
    /   \     \
   3   [7↑]    20
Why: We found the target value, so search ends
Result:
       10
      /    \
     5      15
    /   \     \
   3   [7↑]    20
Answer: Found 7
Annotated Code
DSA Go
package main

import "fmt"

type Node struct {
    val   int
    left  *Node
    right *Node
}

func searchBST(root *Node, target int) *Node {
    curr := root
    for curr != nil {
        if target == curr.val {
            return curr // found target
        } else if target < curr.val {
            curr = curr.left // go left for smaller values
        } else {
            curr = curr.right // go right for bigger values
        }
    }
    return nil // target not found
}

func main() {
    root := &Node{val: 10}
    root.left = &Node{val: 5}
    root.right = &Node{val: 15}
    root.left.left = &Node{val: 3}
    root.left.right = &Node{val: 7}
    root.right.right = &Node{val: 20}

    target := 7
    found := searchBST(root, target)
    if found != nil {
        fmt.Printf("Found %d\n", found.val)
    } else {
        fmt.Printf("Value %d not found\n", target)
    }
}
curr := root
start search at root node
for curr != nil {
continue until we find target or reach end
if target == curr.val {
check if current node is target
return curr // found target
stop search and return node
else if target < curr.val {
go left if target smaller than current
curr = curr.left // go left for smaller values
move to left child
else {
go right if target bigger than current
curr = curr.right // go right for bigger values
move to right child
OutputSuccess
Found 7
Complexity Analysis
Time: O(h) where h is tree height because we follow one path down the tree
Space: O(1) because we use only a few pointers, no extra storage
vs Alternative: Compared to searching an unsorted tree or list which is O(n), BST search is faster if tree is balanced
Edge Cases
Empty tree (root is nil)
Search returns nil immediately, meaning value not found
DSA Go
for curr != nil {
Target value not in tree
Search reaches a nil child and returns nil
DSA Go
for curr != nil {
Target is root node value
Search finds target immediately at root and returns it
DSA Go
if target == curr.val {
When to Use This Pattern
When you need to search or insert values quickly in a sorted way, look for the BST property to guide your path and avoid checking every node.
Common Mistakes
Mistake: Not comparing target with current node value to decide left or right
Fix: Always compare target with current node value to choose correct subtree
Mistake: Going left when target is greater or right when target is smaller
Fix: Follow BST rule: smaller values go left, bigger go right
Summary
It keeps smaller values left and bigger values right to speed up search.
Use it when you want fast search, insert, or delete in sorted data.
The key is comparing target with current node to decide direction.

Practice

(1/5)
1. What is the main property that defines a Binary Search Tree (BST)?
easy
A. Nodes are arranged in a complete binary tree shape
B. Left child nodes have smaller values, right child nodes have larger values
C. All nodes have exactly two children
D. Nodes store only unique values without any order

Solution

  1. Step 1: Understand BST node arrangement

    In a BST, each node's left child contains values smaller than the node, and the right child contains values larger than the node.
  2. Step 2: Compare with other tree types

    Other options describe different tree properties, but only Left child nodes have smaller values, right child nodes have larger values matches the BST property.
  3. Final Answer:

    Left child nodes have smaller values, right child nodes have larger values -> Option B
  4. Quick Check:

    BST property = Left smaller, right larger [OK]
Hint: Remember BST orders left < node < right [OK]
Common Mistakes:
  • Confusing BST with complete binary tree
  • Thinking all nodes must have two children
  • Ignoring the order property of BST
2. Which of the following Go struct definitions correctly represents a node in a BST?
easy
A. type Node struct { value int; left Node; right Node }
B. type Node struct { value int; left *int; right *int }
C. type Node struct { value int; left *Node; right *Node }
D. type Node struct { value int; left interface{}; right interface{} }

Solution

  1. Step 1: Check pointer usage for child nodes

    In Go, child nodes must be pointers to allow nil and recursive structure. type Node struct { value int; left *Node; right *Node } uses *Node pointers correctly.
  2. Step 2: Identify incorrect struct fields

    type Node struct { value int; left Node; right Node } uses Node directly, causing infinite size. type Node struct { value int; left *int; right *int } uses *int which is wrong type. type Node struct { value int; left interface{}; right interface{} } uses interface{}, losing type safety.
  3. Final Answer:

    type Node struct { value int; left *Node; right *Node } -> Option C
  4. Quick Check:

    Use pointers for recursive structs in Go [OK]
Hint: Use *Node for left and right child pointers [OK]
Common Mistakes:
  • Using struct fields instead of pointers for children
  • Using wrong pointer types like *int
  • Using interface{} losing type safety
3. What will be the in-order traversal output of this BST after inserting values in order: 10, 5, 15, 3, 7?
package main
import "fmt"
type Node struct {
  value int
  left, right *Node
}
func inOrder(root *Node) {
  if root == nil {
    return
  }
  inOrder(root.left)
  fmt.Print(root.value, " ")
  inOrder(root.right)
}
func insert(root *Node, val int) *Node {
  if root == nil {
    return &Node{value: val}
  }
  if val < root.value {
    root.left = insert(root.left, val)
  } else {
    root.right = insert(root.right, val)
  }
  return root
}
func main() {
  var root *Node
  vals := []int{10, 5, 15, 3, 7}
  for _, v := range vals {
    root = insert(root, v)
  }
  inOrder(root)
}
medium
A. 3 5 7 10 15
B. 10 5 15 3 7
C. 15 10 7 5 3
D. 5 3 7 10 15

Solution

  1. Step 1: Insert values maintaining BST property

    Insert 10 as root, 5 to left, 15 to right, 3 left of 5, 7 right of 5.
  2. Step 2: Perform in-order traversal

    In-order visits left subtree, node, right subtree. So output is 3 5 7 10 15.
  3. Final Answer:

    3 5 7 10 15 -> Option A
  4. Quick Check:

    In-order traversal of BST = sorted values [OK]
Hint: In-order traversal of BST gives sorted values [OK]
Common Mistakes:
  • Confusing pre-order or post-order with in-order
  • Not inserting nodes correctly in BST
  • Printing values in insertion order
4. The following Go code tries to insert a value into a BST but fails to correctly insert the value. What is the bug?
func insert(root *Node, val int) *Node {
  if root == nil {
    return &Node{value: val}
  }
  if val <= root.value {
    insert(root.left, val)
  } else {
    insert(root.right, val)
  }
  return root
}
medium
A. Missing assignment to root.left or root.right after recursive insert
B. Using <= instead of < causes infinite recursion
C. Returning root instead of new node causes error
D. Function should not return *Node

Solution

  1. Step 1: Analyze recursive insert calls

    The recursive calls insert(root.left, val) and insert(root.right, val) do not assign the returned node back to root.left or root.right.
  2. Step 2: Understand why assignment is needed

    Without assignment, new nodes are not linked to the tree, causing incorrect structure.
  3. Final Answer:

    Missing assignment to root.left or root.right after recursive insert -> Option A
  4. Quick Check:

    Assign recursive insert result to child pointers [OK]
Hint: Always assign recursive insert result to child pointers [OK]
Common Mistakes:
  • Forgetting to assign recursive call results
  • Confusing comparison operators causing infinite loops
  • Ignoring return values in recursive functions
5. You want to check if a binary tree is a valid BST. Which approach correctly verifies the BST property for all nodes?
hard
A. Check only immediate children values against node
B. Check in-order traversal for duplicates only
C. Check tree balance and uniqueness of values
D. Recursively verify all subtree values against node limits

Solution

  1. Step 1: Understand BST validation requirements

    BST property requires all nodes in left subtree to be less than current node and all in right subtree to be greater, not just immediate children.
  2. Step 2: Evaluate each option

    Recursively verify all subtree values against node limits correctly checks recursively with value limits. Check only immediate children values against node only checks immediate children, which can miss violations deeper in the tree.
  3. Final Answer:

    Recursively verify all subtree values against node limits -> Option D
  4. Quick Check:

    BST validation = recursive range checks [OK]
Hint: Check all subtree values recursively, not just children [OK]
Common Mistakes:
  • Checking only immediate children values
  • Confusing balance with BST property
  • Assuming no duplicates means valid BST
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard