Visualize BST search step by step. Watch the algorithm exploit the BST ordering property to eliminate half the remaining tree at each comparison.
About this algorithm
BST search finds a value in a binary search tree by walking a single path down from the root. Every node splits the values below it: smaller ones live in its left subtree and larger ones in its right. So one comparison at each node tells you which side can still hold the target, and the other side is never looked at.
Use BST search when your data lives in a binary search tree and you need to know whether a key is present, or fetch the record stored with it. The other pages in this family build on this walk: insert adds a node where it falls off the tree, and lowest common ancestor runs it for two keys at once. If you only look keys up and never need them in order, a hash map answers in O(1) on average. If the values sit in a sorted array that rarely changes, binary search on the array does the same halving with no pointers. A search tree earns its place when the data changes often and you also want order: the smallest key, the next larger one, or everything between two numbers.
Make the root the current node. An empty tree means the target is not there.
If the target equals the current value, you have found it. If it is smaller, move to the left child; if it is larger, move to the right child. Every value in the other subtree is on the wrong side of this node, so that whole subtree is skipped for good.
Repeat until you find the value or need a child that does not exist. That empty spot is exactly where the value would have to be, so reaching it proves the value is absent. A plain loop does all of this with no recursion and no extra memory.
The page loads seven nodes: 20 at the root, 10 and 30 below it, then 5 and 15 under 10, and 25 and 35 under 30. The search box starts at 15. Compare 15 with 20: smaller, so go left. Compare 15 with 10: larger, so go right. Compare 15 with 15: found, after 3 comparisons, and 30, 25 and 35 were never touched. Now type 27, which is not in the tree. 27 is larger than 20 (go right), smaller than 30 (go left) and larger than 25 (go right), but 25 has no right child, so the page reports "not found" after 3 comparisons. A tree with 3 levels never needs more than 3.
The cost depends on the height, not on how many nodes there are. Insert 5, 10, 15, 20, 25, 30, 35 in that order and each value becomes the right child of the one before, so finding 35 takes 7 comparisons, no better than scanning a list. Self-balancing trees such as AVL and red-black trees rotate nodes after each insert to keep the height close to log N.
Time: each comparison moves one level down, so the work is the height H of the tree: 1 when the target is the root, about log N when the tree is balanced, and N when it is a chain. Space: the loop keeps only a pointer to the current node; a recursive version would use O(H) call stack instead.