Binary Tree

Binary Search Tree Visualizer

What is Binary Search Tree

A binary search tree keeps every value in the left subtree smaller than the node, and every value in the right subtree larger. Search, insert, and the later queries all follow that rule.

insert 5 3 7
query 3 → 1
query 8 → 0

Approach

Start at the root. If the value is smaller, go left. If it is larger, go right. Insert creates a node only when the walk falls off the tree. Duplicates are skipped.

SearchThe same comparison finds a value. If the walk ends at a missing child, the value is absent and the query prints 0.
InsertThe first missing child on that path is where the new node belongs. Nothing already in the tree moves.

The picture inserts the values one at a time, then searches the query values. The practice output is 1 or 0 for each query.

Interactive solution

Insert down the tree, then search
def insert(node, val):
if node is null: return new node
if val < node.val: node.left = insert(node.left, val)
elif val > node.val: node.right = insert(node.right, val)
return node
search uses the same comparisons
Step 0/0 Answer —

The finished tree is on screen when the page opens. Next and Play start again from the first step. The play controls sit under the tree and the pseudocode.

Complexity

PieceCostWhy
Search or insertO(h)Each comparison moves one level down.
BuildO(n h)n inserts. A sorted insert order makes a spine, so h can be n.

Implementation

def insert(node, val):
    if not node:
        return TreeNode(val)
    if val < node.val:
        node.left = insert(node.left, val)
    elif val > node.val:
        node.right = insert(node.right, val)
    return node

def search(node, val):
    while node:
        if val == node.val: return True
        node = node.left if val < node.val else node.right
    return False