Imagine you want to find a number in a Binary Search Tree (BST). What is the main idea behind the search process?
Think about how the BST organizes values to help find numbers quickly.
In a BST, each node's left child has smaller values and the right child has larger values. This lets you decide which path to take at each step, making the search efficient.
Consider a Binary Search Tree with n nodes. What is the worst-case time complexity to search for a value?
Think about what happens if the tree is not balanced.
If the BST is unbalanced and looks like a linked list, you may have to check every node, making the search take O(n) time.
Given the BST below, what node will the search end on when looking for the value 15?
Tree structure (each node: value):
- Root: 10
- Left child of 10: 5
- Right child of 10: 20
- Left child of 20: 15
- Right child of 20: 25
Follow the BST search steps comparing 15 with each node value.
Start at 10, 15 is greater so go right to 20. Then 15 is less than 20, go left to 15. Found the node with value 15.
Consider searching for the value 13 in the BST below:
- Root: 10
- Left child of 10: 5
- Right child of 10: 20
- Left child of 20: 15
- Right child of 20: 25
What is the result of the search?
Think about how the search moves down the tree and what happens when it can't go further.
Searching for 13 goes 10 -> 20 -> 15. Since 13 is less than 15, the search tries to go left but finds no child, so it stops, confirming 13 is not present.
Why does balancing a BST improve the efficiency of searching compared to an unbalanced BST?
Consider how the height of the tree relates to the number of steps in searching.
A balanced BST keeps its height minimal, about log(n), so searching requires fewer steps compared to a tall, unbalanced tree that can have height n.