Trees - Introduction

What a binary tree is, the four ways to visit every node, and how a binary search tree finds a value, in Java.

A tree stores things that branch. A folder on your computer holds folders, which hold more folders, and every folder sits inside exactly one parent folder. In a binary tree, every item has at most two items directly below it: a left one and a right one. Most tree problems ask you to visit every item once, in a sensible order, and combine what you find there. The small tree in the picture below is the example for every idea that follows.

The tree [5, 3, 8, 1, 4, null, 9]: root 5 at depth 0, children 3 and 8 at depth 1, leaves 1, 4 and 9 at depth 2, with the left subtree of 5 in a dashed box and the missing left child of 8 marked null.

Root, children and leaves

In the picture above, each circle is a node and holds one number. The orange node, 5, is the root: the node with nothing above it. The two nodes joined to 5 from below, 3 and 8, are its children, and 5 is their parent. Node 3 has two children, 1 and 4, while node 8 has a single child, 9, on its right.

The teal nodes 1, 4 and 9 have no children at all. A node like that is a leaf.

Now look at the dashed box labelled "left subtree of 5". It holds 3 and everything below it. That part is a small tree of its own, with 3 as its root. In the same way, 8 with 9 below it is the right subtree of 5. Many tree methods lean on this: solve the question for the left subtree, solve it for the right subtree, then combine the two answers at the node.

The labels "depth 0" to "depth 2" on the left of the picture count steps down from the root. The depth of a node is the number of lines, called edges, between it and the root. Node 5 is at depth 0, nodes 3 and 8 at depth 1, and the leaves at depth 2. The height of the tree is its largest depth, here 2. Some books count nodes instead of edges and would say 3; here height always counts edges.

Problems write a tree as one list, row by row from the top and left to right: [5, 3, 8, 1, 4, null, 9]. After the root 5 come its children 3 and 8, then the children of 3, then the children of 8. Node 8 has no left child, so that spot holds null, the dashed "null" box in the picture. The leaves' missing children would all come at the end, so they are left out.

A tree node in Java

How does a program hold such a tree? Each node becomes one small object with its value and two references, one to its left child and one to its right child. A missing child is simply null.

Java
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int val) {
        this.val = val;
    }
}

The program only keeps the root. From node 5 it follows left to 3, and left again to 1, while node 8's left is null. Two small helpers convert between the forms: build turns the list into nodes, and show prints nodes back as a list.

Depth-first: preorder, inorder and postorder

Suppose you want every value in the tree. A natural way is to start at the root, go down one side as deep as you can, and only then come back up and try the other side. A walk that finishes the deepest part of one branch before it moves to the next branch is called depth-first search, or DFS for short.

In code, the walk is a method that handles one node and then calls itself twice, once on the left child and once on the right child. On the example tree, preorder(5) records 5 and calls preorder on node 3. That call records 3 and calls preorder on node 1, and so on down. A call on a missing child gets null and returns at once, and that check is what makes the calls stop.

One choice is left: is the node recorded before the two calls, between them or after them? The three answers give three orders. The small orange number next to each node in the picture is its place in that order.

Three copies of the tree. Preorder gives 5, 3, 1, 4, 8, 9. Inorder gives 1, 3, 4, 5, 8, 9. Postorder gives 1, 4, 3, 9, 8, 5. Each node has a small orange number with its place in the order.
  • Preorder (node, left, right) records the node before its subtrees. The root 5 gets number 1, and the order is 5, 3, 1, 4, 8, 9. Preorder suits work that must happen before the children, such as copying a tree or handing a value down from the root.
  • Inorder (left, node, right) records the whole left subtree first. Node 5 waits until 1, 3 and 4 are recorded, so it gets number 4, and the order is 1, 3, 4, 5, 8, 9. Those values come out sorted, and that is no accident. This tree keeps smaller values to the left of each node, and a tree like that is called a binary search tree.
  • Postorder (left, right, node) finishes both subtrees before the node. The root 5 comes last with number 6, and the order is 1, 4, 3, 9, 8, 5. Postorder suits answers that are built from the children's answers.

Combining the children's answers

What does "built from the children's answers" look like? Height is the clearest case. An empty subtree counts as -1, so a leaf gets 1 + max(-1, -1) = 0. Node 3 then gets 1 + max(0, 0) = 1 from its leaves 1 and 4, node 8 also gets 1, and the root gets 1 + max(1, 1) = 2. Each node needs both answers first, so the work happens after the two calls return.

The same heights give one more word. A tree is balanced when, at every node, the heights of the two subtrees differ by at most 1. At 5 they are 1 and 1, at 3 they are 0 and 0, and at 8 they are -1 (no left child) and 0, so the example tree is balanced.

Breadth-first: level order with a queue

Some questions are about rows: the average of each level, or the rightmost node of each row. A depth-first walk jumps between rows, so these need a different walk. It visits everything at depth 0, then everything at depth 1, and so on. Covering the whole width of one level before going a level deeper is called breadth-first search, or BFS. On a tree it is also called level order.

The tool for it is a queue: a line where nodes join at the back and leave from the front. In Java, the ArrayDeque class from java.util works as such a queue: add puts a tree node at the back and poll takes one from the front. The queue starts with the root. At the start of each round, note how many nodes the queue holds, because that is exactly one level. Take that many nodes from the front, record each one, and add its children at the back for the next round.

Level order on the tree. Round 1 starts with queue [5] and adds 3 and 8. Round 2 starts with [3, 8] and adds 1, 4 and 9. Round 3 starts with [1, 4, 9] and adds none.

Follow the table on the right of the picture, with its columns "round", "queue at start" and "children added". Round 1 starts with the queue holding 5, and taking 5 out adds 3 and 8. Round 2 starts with 3 and 8, all of level 1, and adds 1, 4 and 9. Round 3 starts with level 2 and adds none, so the queue empties and the walk ends with the levels [5], [3, 8] and [1, 4, 9].

Binary search trees

Look once more at the example tree. Every value in the left subtree of 5 (1, 3 and 4) is smaller than 5, and every value in its right subtree (8 and 9) is larger. The same holds at 3 and at 8. A binary tree where this holds at every node is a binary search tree, or BST.

Why does that rule help? Say you want to know whether 4 is in the tree. In an ordinary binary tree, 4 could sit anywhere, so the safe way is to visit every node, all six of them. In a BST, one comparison at each node tells you which side to try next.

Left: searching the tree for 4 follows 5, then 3, then 4. Right: the same six values inserted in sorted order form a line 1, 3, 4, 5, 8, 9 of height 5.

The orange path on the left of the picture is the search for 4. Since 4 is smaller than 5, the search goes left to 3. Since 4 is larger than 3, it goes right and finds 4. It checked three nodes, one per level, and never touched the right subtree of 5. A search for 7 goes right at 5, then left at 8, finds no node there, and stops: 7 is not in the tree.

How much that saves depends on the shape. The right side of the picture, labelled "sorted inserts 1, 3, 4, 5, 8, 9", holds the same six values added one by one in sorted order. Each new value is larger than all before it, so it always goes right, and the tree becomes a line of height 5. Finding 9 there checks all six nodes. A search costs one step per level, so it pays off when the tree is short and wide.

The Java template

Here is everything so far as one program. The three depth-first orders are short methods that call themselves on each child. The height method is the postorder walk that combines the children's answers, and levelOrder is the queue walk. For the BST, searchPath walks down from the root and returns the values it checked, and insert puts a new value where a search for it would end. The helpers build and show convert between nodes and the list form.

The main method runs the example tree, an empty tree, a tree with one node, and the six values inserted in sorted order.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Queue;

public class TreesIntro {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    // Depth-first: the three orders differ only in where out.add(node.val) sits.
    static void preorder(TreeNode node, List<Integer> out) {   // node, left, right
        if (node == null) {
            return;
        }
        out.add(node.val);
        preorder(node.left, out);
        preorder(node.right, out);
    }

    static void inorder(TreeNode node, List<Integer> out) {    // left, node, right
        if (node == null) {
            return;
        }
        inorder(node.left, out);
        out.add(node.val);
        inorder(node.right, out);
    }

    static void postorder(TreeNode node, List<Integer> out) {  // left, right, node
        if (node == null) {
            return;
        }
        postorder(node.left, out);
        postorder(node.right, out);
        out.add(node.val);
    }

    // Postorder that combines the children's answers: height counted in edges.
    static int height(TreeNode node) {
        if (node == null) {
            return -1; // an empty tree is one level below a leaf
        }
        return 1 + Math.max(height(node.left), height(node.right));
    }

    // Breadth-first: a queue, one level per round of the outer loop.
    static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> levels = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        if (root != null) {
            queue.add(root);
        }
        while (!queue.isEmpty()) {
            int size = queue.size(); // how many nodes are on this level
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            levels.add(level);
        }
        return levels;
    }

    // Binary search tree: go left for smaller values, right for larger ones.
    static List<Integer> searchPath(TreeNode root, int target) {
        List<Integer> path = new ArrayList<>();
        TreeNode node = root;
        while (node != null) {
            path.add(node.val);
            if (target == node.val) {
                return path;
            }
            node = target < node.val ? node.left : node.right;
        }
        return path; // fell off the tree: target is not there
    }

    static TreeNode insert(TreeNode node, int value) {
        if (node == null) {
            return new TreeNode(value);
        }
        if (value < node.val) {
            node.left = insert(node.left, value);
        } else {
            node.right = insert(node.right, value);
        }
        return node;
    }

    // Helper: build a tree from the row-by-row form, null meaning "no child here".
    static TreeNode build(Integer... values) {
        if (values.length == 0 || values[0] == null) {
            return null;
        }
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> parents = new ArrayDeque<>();
        parents.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode parent = parents.poll();
            if (values[i] != null) {
                parent.left = new TreeNode(values[i]);
                parents.add(parent.left);
            }
            i++;
            if (i < values.length && values[i] != null) {
                parent.right = new TreeNode(values[i]);
                parents.add(parent.right);
            }
            i++;
        }
        return root;
    }

    // Helper: print a tree back in the same row-by-row form.
    static String show(TreeNode root) {
        List<Integer> out = new ArrayList<>();
        List<TreeNode> order = new ArrayList<>();
        order.add(root);
        for (int i = 0; i < order.size(); i++) {
            TreeNode node = order.get(i);
            out.add(node == null ? null : node.val);
            if (node != null) {
                order.add(node.left);
                order.add(node.right);
            }
        }
        while (!out.isEmpty() && out.get(out.size() - 1) == null) {
            out.remove(out.size() - 1);
        }
        return out.toString();
    }

    static void report(String name, TreeNode root) {
        List<Integer> pre = new ArrayList<>();
        List<Integer> in = new ArrayList<>();
        List<Integer> post = new ArrayList<>();
        preorder(root, pre);
        inorder(root, in);
        postorder(root, post);
        System.out.println(name + " " + show(root));
        System.out.println("  preorder:    " + pre);
        System.out.println("  inorder:     " + in);
        System.out.println("  postorder:   " + post);
        System.out.println("  level order: " + levelOrder(root));
        System.out.println("  height:      " + height(root));
    }

    static String search(TreeNode root, int target) {
        List<Integer> path = searchPath(root, target);
        boolean found = !path.isEmpty() && path.get(path.size() - 1) == target;
        return path + (found ? " found" : " not found");
    }

    public static void main(String[] args) {
        TreeNode root = build(5, 3, 8, 1, 4, null, 9);
        report("Tree", root);
        System.out.println("  search 4:    " + search(root, 4));
        System.out.println("  search 7:    " + search(root, 7));

        report("Empty tree", build());
        report("One node", build(7));

        TreeNode line = null;
        for (int value : new int[] {1, 3, 4, 5, 8, 9}) {
            line = insert(line, value); // same values, inserted in sorted order
        }
        System.out.println("Sorted inserts " + show(line));
        System.out.println("  height:      " + height(line));
        System.out.println("  search 9:    " + search(line, 9));
    }
}

Running it prints:

Output
Tree [5, 3, 8, 1, 4, null, 9]
  preorder:    [5, 3, 1, 4, 8, 9]
  inorder:     [1, 3, 4, 5, 8, 9]
  postorder:   [1, 4, 3, 9, 8, 5]
  level order: [[5], [3, 8], [1, 4, 9]]
  height:      2
  search 4:    [5, 3, 4] found
  search 7:    [5, 8] not found
Empty tree []
  preorder:    []
  inorder:     []
  postorder:   []
  level order: []
  height:      -1
One node [7]
  preorder:    [7]
  inorder:     [7]
  postorder:   [7]
  level order: [[7]]
  height:      0
Sorted inserts [1, null, 3, null, 4, null, 5, null, 8, null, 9]
  height:      5
  search 9:    [1, 3, 4, 5, 8, 9] found

The first block matches the pictures: preorder [5, 3, 1, 4, 8, 9], inorder [1, 3, 4, 5, 8, 9], postorder [1, 4, 3, 9, 8, 5] and level order [[5], [3, 8], [1, 4, 9]]. The search for 4 prints [5, 3, 4] found, the orange path. The search for 7 prints [5, 8] not found: it stopped at the missing left child of 8.

Every method checks for null first, so the empty tree [] gives empty lists and a height of -1, and the one-node tree [7] has height 0. The last block is the line from the picture. Its list form, [1, null, 3, null, 4, null, 5, null, 8, null, 9], has a null for every missing left child, and the search for 9 passes through all six values.

Choosing the walk for a problem

Given a tree problem, which walk fits? Ask what each node needs to know.

  • It needs its children's answers (height, size, sums, whether two subtrees match): use postorder and combine after the two calls, as height does.
  • It needs something from above (the sum along the path so far, the largest value on the way down): use preorder and pass that value as an extra argument to both calls.
  • The question talks about levels or rows (per-level averages, the view from one side): use level order, and read the queue's size at the start of each round.
  • The tree is a BST and the question is about order (the smallest values, a sorted list, finding a value): use inorder, or walk down one path by comparing, as searchPath does.

Traps worth knowing

Two mistakes are easy to make in tree code. The program below runs both, on the example tree and on a changed copy of it.

Reading the queue size inside the loop

The level-order walk reads queue.size() once, before the inner loop, and keeps it in size. It is tempting to put queue.size() straight into the loop condition instead. But the queue grows while the loop runs, because each node adds its children, so the loop takes nodes from the next level too.

Checking a BST against the children alone

Is [5, 3, 8, 1, 6, null, 9] a BST? It is the example tree with 4 replaced by 6. Node 6 is the right child of 3 and larger than 3, so every parent and child pair looks right. But 6 sits in the left subtree of 5 and is larger than 5. The fix passes down the range each node must fall in: going left from 5 sets the upper limit to 5, and 6 breaks it. That is the preorder pattern of passing a value down, and Validate Binary Search Tree builds on it.

Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class TreeTraps {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    // Trap 1: queue.size() is read again on every pass of the inner loop.
    static List<List<Integer>> levelOrderWrong(TreeNode root) {
        List<List<Integer>> levels = new ArrayList<>();
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < queue.size(); i++) { // the size grows as children are added
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
            levels.add(level);
        }
        return levels;
    }

    // Trap 2: checking each node only against its own two children.
    static boolean isBstChildrenOnly(TreeNode node) {
        if (node == null) {
            return true;
        }
        if (node.left != null && node.left.val >= node.val) {
            return false;
        }
        if (node.right != null && node.right.val <= node.val) {
            return false;
        }
        return isBstChildrenOnly(node.left) && isBstChildrenOnly(node.right);
    }

    // Fix: every node must sit inside the range its ancestors allow.
    static boolean isBst(TreeNode node, long low, long high) {
        if (node == null) {
            return true;
        }
        if (node.val <= low || node.val >= high) {
            return false;
        }
        return isBst(node.left, low, node.val) && isBst(node.right, node.val, high);
    }

    static TreeNode build(Integer... values) {
        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> parents = new ArrayDeque<>();
        parents.add(root);
        int i = 1;
        while (i < values.length) {
            TreeNode parent = parents.poll();
            if (values[i] != null) {
                parent.left = new TreeNode(values[i]);
                parents.add(parent.left);
            }
            i++;
            if (i < values.length && values[i] != null) {
                parent.right = new TreeNode(values[i]);
                parents.add(parent.right);
            }
            i++;
        }
        return root;
    }

    public static void main(String[] args) {
        TreeNode root = build(5, 3, 8, 1, 4, null, 9);
        System.out.println("Size read in the loop: " + levelOrderWrong(root));

        TreeNode broken = build(5, 3, 8, 1, 6, null, 9); // 6 sits left of 5
        System.out.println("Children-only check: " + isBstChildrenOnly(broken));
        System.out.println("Range check:         "
                + isBst(broken, Long.MIN_VALUE, Long.MAX_VALUE));
        System.out.println("Range check on [5, 3, 8, 1, 4, null, 9]: "
                + isBst(root, Long.MIN_VALUE, Long.MAX_VALUE));
    }
}

Running it prints:

Output
Size read in the loop: [[5, 3, 8], [1, 4], [9]]
Children-only check: true
Range check:         false
Range check on [5, 3, 8, 1, 4, null, 9]: true

The first line shows the size trap: [[5, 3, 8], [1, 4], [9]] instead of [[5], [3, 8], [1, 4, 9]]. In the first round the size was 1 when the loop began, 2 after 5 was taken out and 3 after 3 was taken out, so the loop kept going and 3 and 8 landed in the root's level. For the broken tree, the children-only check says true and the range check says false. The last line shows that the range check still accepts the example tree.

Complexity

Write n for the number of nodes and h for the height of the tree.

  • Traversals and height: O(n) time, because each of the n nodes is visited once and each call on a missing child returns straight away.
  • Depth-first walks: O(h) extra space, because the calls still waiting to finish form a chain from the root to the current node, one per level. For the sorted-inserts line, h is n - 1, so that is O(n).
  • Level order: O(w) extra space, where w is the largest number of nodes on one level, because the queue holds the rest of one level plus the children added so far.
  • BST search and insert: O(h) time, because each step goes down one level. That was three nodes checked for 4 in the example tree, and six for 9 in the line.

Where to go next

Postorder: combine the children's answers

Preorder: pass a value down

Level order with a queue

Binary search trees