Stop 10 · Data Structures & Algorithms in JavaTopics · 8/11

Trees & Binary Search Trees

Part of the Java Roadmap

In short

Folders on your laptop, the HTML of a web page and Java's own TreeMap are all trees. Binary search trees add one rule that makes searching as quick as flipping through a sorted list.

Trees are hierarchical structures. In a binary search tree, left children are smaller and right children are larger, giving O(log n) operations when the tree is balanced.

The jaadu climbs a big branching tree, choosing the left or right branch at each fork while holding a lantern.

Think of it like this

The family tree with a rule

Picture a family tree where every younger sibling's line goes to the left and every older one to the right. To find someone born in 1995, you start at the eldest ancestor and keep asking 'before or after?'. Each answer rules out a whole branch of the family.

Watch it happen

Searching a BST for 60

50
30
70
20
40
60
80

1/4Start at the root, 50. 60 is bigger, so go right.

The big ideas

What you need to know

Tree words

Root, parent, child, leaf, height and depth. A binary tree has at most two children per node.

The BST rule

Everything in the left subtree is smaller and everything in the right subtree is larger, at every node.

Traversals

Pre-order (node first), in-order (sorted for a BST), post-order (children first) and level-order with a queue.

Balance matters

Balanced, it is O(log n). Insert sorted data into a plain BST and it becomes a slow O(n) line. TreeMap uses a self-balancing red-black tree.

See it in code

Walk through the code

java
1public class BST {2    static class Node {3        int val;4        Node left, right;5        Node(int val) { this.val = val; }6    }7 8    static Node insert(Node root, int val) {9        if (root == null) return new Node(val);10        if (val < root.val) root.left = insert(root.left, val);11        else if (val > root.val) root.right = insert(root.right, val);12        return root;13    }14 15    static boolean contains(Node root, int val) {16        while (root != null) {17            if (val == root.val) return true;18            root = val < root.val ? root.left : root.right;19        }20        return false;21    }22 23    static void inorder(Node root) {24        if (root == null) return;25        inorder(root.left);26        System.out.print(root.val + " ");27        inorder(root.right);28    }29 30    static int height(Node root) {31        if (root == null) return 0;32        return 1 + Math.max(height(root.left), height(root.right));33    }34 35    public static void main(String[] args) {36        Node root = null;37        for (int v : new int[] {50, 30, 70, 20, 40, 60, 80}) root = insert(root, v);38        System.out.println(contains(root, 60));  // true39        inorder(root);                           // 20 30 40 50 60 70 8040    }41}

1/4Recursive insert: walk left or right until an empty spot, then attach a new node there.

Insert, search, in-order traversal and height on a small BST.

Save yourself the pain

Common mistakes

Oops

Only checking node.left.val < node.val < node.right.val to validate a BST.

Do this instead

The rule applies to whole subtrees. Pass down a min and max range as you recurse.

Oops

Forgetting the null base case in tree recursion.

Do this instead

Start almost every tree method with if (root == null) return ...;

Your mission

Tree workout

~60 min

Quick check

Which traversal prints the values of a BST in ascending order?

Go deeper

  1. 1Implement inorder, preorder, postorder and level-order traversal.
  2. 2Insert and search in a BST you build yourself.
  3. 3Solve 'maximum depth' and 'validate BST' problems.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge