Back to DSA Python report

Binary Tree Search

Interactive notes for inorder search logic, recursive short-circuiting, and a clickable dry run.

Binary Tree: Inorder Search Logic

Searching in a Binary Tree (not necessarily a BST) requires visiting nodes. Using Inorder means we check the Left Child, then the Current Node, then the Right Child.

Key Concept: Short-Circuiting
To be efficient, if we find the value in the left subtree, we stop and return True immediately without checking the root or the right subtree.

The Code

def inorder_search(node, target):
    # Base Case: Reach a leaf's child
    if node is None:
        return False

    # 1. Search Left
    if inorder_search(node.left, target):
        return True

    # 2. Check Current
    if node.val == target:
        return True

    # 3. Search Right
    return inorder_search(node.right, target)

Interactive Dry Run (Target: 4)

Click a row to see the state.

Step Call Action Return
1 search(5, 4) Go Left Pending
2 search(1, 4) Check Value (1 != 4) False
3 search(5, 4) Left failed. Check 5 == 4? No
4 search(5, 4) Go Right -> search(3, 4) Pending
5 search(3, 4) Go Left -> search(4, 4) Pending
6 search(4, 4) Check 4 == 4? True
7 search(3, 4) Propagate True from Left True
8 search(5, 4) Propagate True from Right True