DSA
    intermediate

    Binary Search Tree (BST)

    Software Engineer path · lesson 16 of 99
    O(h) ops

    Syntax: insert n · search n · delete n · inorder · preorder · postorder · levelorder. Numbers from -99 to 99.

    Try:

    Empty tree

    ComparingPath so farFoundChangedSuccessorVisitingVisited (traversal)Duplicate

    Empty tree. Run the operations in order.

    Code (running line highlighted)
    1. 1insert(x): node = root
    2. 2 while node: node = node.left if x < node.val else node.right
    3. 3 attach x where the walk fell off the tree
    4. 4search(x): walk the same way; stop when node.val == x
    5. 5delete(x): find x
    6. 6 0 or 1 child: replace x with that child
    7. 7 2 children: copy the in-order successor into x, delete the successor
    8. 8traverse: in-order (L, node, R) · pre-order (node, L, R) · post-order (L, R, node) · level-order (queue)
    Comparisons
    0 / 15
    Invariant: For every node: everything in its left subtree is smaller, everything in its right subtree is larger.

    height 0, 0 nodes

    Tap any element in the diagram to inspect its state at this step.

    1 / 26

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    In-order traversal

    Sequence

    Keys 50, 30, 70, 20, 40 were inserted into an empty BST. Order the keys as an in-order traversal visits them.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    What is the worst-case time complexity of searching in a BST?

    When to reach for this

    • When you need to maintain a **Sorted** collection
    • When you need fast Lookup, Insert, and Delete (O(log n))
    • Finding the closest value, floor, or ceiling

    Interview Questions

    Facebook
    Amazon
    Bloomberg
    Microsoft
    Apple
    Amazon
    Google
    Google
    Airbnb
    Microsoft

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required