Bird
Raised Fist0
Data Structures Theoryknowledge~6 mins

Searching in BST in Data Structures Theory - Full Explanation

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Imagine you have a large collection of sorted books and you want to find a specific title quickly. Searching through them one by one would take too long. This is where a Binary Search Tree helps by organizing data so you can find what you want faster.
Explanation
Binary Search Tree Structure
A Binary Search Tree (BST) is a special kind of tree where each node has at most two children. The left child contains values smaller than the node, and the right child contains values larger than the node. This order helps in quickly deciding where to look next when searching.
BST keeps data organized so that smaller values go left and larger values go right, enabling efficient searching.
Search Process in BST
To search for a value, start at the root node. Compare the value you want with the current node's value. If they match, you found it. If the value is smaller, move to the left child; if larger, move to the right child. Repeat this until you find the value or reach a leaf node without success.
Searching in BST uses comparisons to decide which branch to follow, reducing the search area at each step.
Efficiency of Searching
Because each step cuts the search space roughly in half, searching in a balanced BST takes about log base 2 of n steps, where n is the number of nodes. This is much faster than checking every node one by one in a list.
BST search is efficient, taking time proportional to the height of the tree, often much less than checking all items.
When Search Fails
If the search reaches a point where there is no left or right child to follow and the value is not found, it means the value is not in the tree. This is a clear stopping point for the search.
Reaching a missing child during search means the value does not exist in the BST.
Real World Analogy

Imagine looking for a friend's name in a phone book organized alphabetically. You open the book near the middle and check the name. If your friend's name comes before that, you look in the first half; if after, you look in the second half. You keep splitting the search area until you find the name or realize it’s not there.

Binary Search Tree Structure → Phone book sorted alphabetically with names split into two halves
Search Process in BST → Opening the phone book at a point and deciding which half to search next
Efficiency of Searching → Cutting the search area in half each time to find the name quickly
When Search Fails → Reaching a point where the name should be but is missing, so you stop searching
Diagram
Diagram
        ┌─────50─────┐
        │             │
     ┌─30─┐         ┌─70─┐
     │    │         │    │
   ┌2040        60   80
   │   │           │     │
  10  25         55    90
A simple Binary Search Tree showing nodes with smaller values on the left and larger on the right.
Key Facts
Binary Search Tree (BST)A tree where each node's left child has smaller values and right child has larger values.
Search in BSTStart at root, compare value, move left if smaller, right if larger, repeat until found or no child.
Search EfficiencySearch time is proportional to the tree height, often about log base 2 of the number of nodes.
Search FailureIf no child exists where the search should continue, the value is not in the BST.
Code Example
Data Structures Theory
class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

def search_bst(root, target):
    current = root
    while current:
        if target == current.value:
            return True
        elif target < current.value:
            current = current.left
        else:
            current = current.right
    return False

# Example tree
root = Node(50)
root.left = Node(30)
root.right = Node(70)
root.left.left = Node(20)
root.left.right = Node(40)
root.right.left = Node(60)
root.right.right = Node(80)

print(search_bst(root, 60))  # True
print(search_bst(root, 25))  # False
OutputSuccess
Common Confusions
Assuming BST search always takes the same time regardless of tree shape
Assuming BST search always takes the same time regardless of tree shape Search time depends on tree height; if the tree is unbalanced and looks like a list, search can be slow.
Thinking BST nodes can have more than two children
Thinking BST nodes can have more than two children By definition, BST nodes have at most two children: left and right.
Summary
A Binary Search Tree organizes data so smaller values go left and larger go right, making search faster.
Searching starts at the root and moves left or right based on comparisons until the value is found or not present.
Search speed depends on the tree's shape; balanced trees allow quick searches, while unbalanced ones can slow down.

Practice

(1/5)
1. What is the main advantage of searching in a Binary Search Tree (BST)?
easy
A. It allows faster search by using the order of elements
B. It stores elements in random order for quick access
C. It uses hashing to find elements instantly
D. It searches all nodes one by one sequentially

Solution

  1. Step 1: Understand BST property

    A BST keeps elements ordered so smaller values are on the left and larger on the right.
  2. Step 2: Use order for searching

    This order lets us decide to go left or right, skipping half the tree each step, making search faster.
  3. Final Answer:

    It allows faster search by using the order of elements -> Option A
  4. Quick Check:

    BST order speeds search = It allows faster search by using the order of elements [OK]
Hint: BST order guides search direction quickly [OK]
Common Mistakes:
  • Thinking BST stores elements randomly
  • Confusing BST with hashing
  • Assuming linear search in BST
2. Which of the following is the correct way to decide the next node to visit when searching for a value in a BST?
easy
A. Go left if target is greater than current node
B. Go left if target is smaller than current node
C. Go right if target is smaller than current node
D. Always go to the root node

Solution

  1. Step 1: Recall BST search rule

    If the target is smaller than the current node's value, we move to the left child.
  2. Step 2: Apply rule to options

    Go left if target is smaller than current node correctly states to go left if target is smaller, which matches BST property.
  3. Final Answer:

    Go left if target is smaller than current node -> Option B
  4. Quick Check:

    Smaller target -> left child = Go left if target is smaller than current node [OK]
Hint: Smaller target means go left in BST [OK]
Common Mistakes:
  • Reversing left and right directions
  • Ignoring BST ordering rules
  • Always going to root node
3. Consider the BST below:
      15
     /  \
    10  20
   /    / \
  8    17 25

Which nodes will be visited when searching for the value 17?
medium
A. [10, 8, 17]
B. [15, 10, 8]
C. [15, 20, 25]
D. [15, 20, 17]

Solution

  1. Step 1: Start at root and compare with 17

    Root is 15. Since 17 > 15, move right to 20.
  2. Step 2: Compare 20 with 17

    17 < 20, so move left to 17, which matches the target.
  3. Final Answer:

    [15, 20, 17] -> Option D
  4. Quick Check:

    Path to 17 = 15 -> 20 -> 17 [OK]
Hint: Follow BST rules: left if smaller, right if larger [OK]
Common Mistakes:
  • Going left from 15 when target is larger
  • Skipping nodes in path
  • Confusing node values
4. You wrote code to search a BST but it always returns None even when the value exists. What is the most likely mistake?
medium
A. Not moving to left child when target is smaller
B. Using a queue instead of recursion
C. Always moving to left child regardless of target
D. Checking only the root node

Solution

  1. Step 1: Understand BST search logic

    Search must move left if target is smaller, right if larger.
  2. Step 2: Identify error in always moving left

    If code always moves left, it misses nodes on the right side where target might be.
  3. Final Answer:

    Always moving to left child regardless of target -> Option C
  4. Quick Check:

    Wrong direction causes search failure = Always moving to left child regardless of target [OK]
Hint: Move left or right based on comparison, not always left [OK]
Common Mistakes:
  • Ignoring right subtree
  • Checking only root node
  • Using wrong data structure for traversal
5. Given a BST where some nodes have duplicate values on the right subtree, how should the search algorithm be adapted to find all occurrences of a target value?
hard
A. Traverse both left and right subtrees when node equals target
B. Search left subtree only once target is found
C. Stop search immediately after first match
D. Ignore duplicates and return first found

Solution

  1. Step 1: Understand duplicates in BST

    Duplicates are stored in right subtree, so multiple matches can exist there.
  2. Step 2: Adapt search to find all matches

    When a node equals target, search both left (for smaller) and right (for duplicates) subtrees to find all occurrences.
  3. Final Answer:

    Traverse both left and right subtrees when node equals target -> Option A
  4. Quick Check:

    Check both sides for duplicates = Traverse both left and right subtrees when node equals target [OK]
Hint: Check both subtrees when value matches to find duplicates [OK]
Common Mistakes:
  • Stopping after first match
  • Ignoring right subtree duplicates
  • Searching only one subtree