Skip to lesson

Practice: binary trees

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Solving diverse tree problems strengthens traversal choices and structural recursive reasoning.

Symmetric trees, identical trees and inverting

Two trees are identical when their values and child shapes match node for node. A tree is symmetric when its left and right subtrees mirror each other across the root. A helper function compares two nodes by checking opposite branches.

Example 1 · Symmetric and Inverted Binary Trees

Main.javaJava
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static boolean isMirror(TreeNode t1, TreeNode t2) {        if (t1 == null && t2 == null) return true;        if (t1 == null || t2 == null) return false;        return (t1.val == t2.val)            && isMirror(t1.left, t2.right)            && isMirror(t1.right, t2.left);    }
    static boolean isSymmetric(TreeNode root) {        return root == null || isMirror(root.left, root.right);    }
    static TreeNode invert(TreeNode root) {        if (root == null) return null;        TreeNode temp = root.left;        root.left = invert(root.right);        root.right = invert(temp);        return root;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(1);        root.left = new TreeNode(2);        root.right = new TreeNode(2);        root.left.left = new TreeNode(3);        root.right.right = new TreeNode(3);
        System.out.println("Is symmetric: " + isSymmetric(root));        invert(root);        System.out.println("Root left val after invert: " + root.left.val);    }}
Output
Is symmetric: true
Root left val after invert: 2

What this code does

  • The mirror helper compares values and crosses left with right recursive checks.
  • Inverting recursively swaps child references at every node in the tree.
  • Both algorithms visit every node once, operating in O(n) time.

Node 1 matches node 2 only if their values match and outer children mirror each other. That means t1.left must mirror t2.right, and t1.right must mirror t2.left. Inverting a tree swaps the left child pointer and right child pointer at every node. Recursively invert the left child, invert the right child, and swap the two pointers. Every mirror operation runs in linear time visiting all n nodes.

Maximum width and burning a binary tree

Maximum width gives each node a heap-style index (left child 2i+1, right child 2i+2) and compares the first and last index on a level. Burning a tree spreads fire to children and parent each minute.

Example 2 · Maximum Width with Level Normalization

Main.javaJava
import java.util.LinkedList;import java.util.Queue;
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static class Pair {        TreeNode node;        long idx;        Pair(TreeNode node, long idx) {            this.node = node;            this.idx = idx;        }    }
    static int widthOfBinaryTree(TreeNode root) {        if (root == null) return 0;        Queue<Pair> queue = new LinkedList<>();        queue.offer(new Pair(root, 0));        long maxWidth = 0;
        while (!queue.isEmpty()) {            int size = queue.size();            long minIdx = queue.peek().idx;            long first = 0, last = 0;
            for (int i = 0; i < size; i++) {                Pair curr = queue.poll();                long curIdx = curr.idx - minIdx;                if (i == 0) first = curIdx;                if (i == size - 1) last = curIdx;
                if (curr.node.left != null) {                    queue.offer(new Pair(curr.node.left, 2 * curIdx + 1));                }                if (curr.node.right != null) {                    queue.offer(new Pair(curr.node.right, 2 * curIdx + 2));                }            }            maxWidth = Math.max(maxWidth, last - first + 1);        }        return (int) maxWidth;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(1);        root.left = new TreeNode(3);        root.right = new TreeNode(2);        root.left.left = new TreeNode(5);        root.right.right = new TreeNode(9);
        System.out.println("Max width: " + widthOfBinaryTree(root));    }}
Output
Max width: 4

What this code does

  • Heap style index assignment assigns 2 * i + 1 and 2 * i + 2 to children.
  • Subtracting the minimum index per level prevents integer overflow on deep trees.
  • The width calculation includes intermediate null positions between boundary nodes.

Example 3 · Burn Binary Tree with BFS

Main.javaJava
import java.util.*;
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static void mapParents(TreeNode root, Map<TreeNode, TreeNode> parents) {        Queue<TreeNode> q = new LinkedList<>();        q.offer(root);        while (!q.isEmpty()) {            TreeNode curr = q.poll();            if (curr.left != null) {                parents.put(curr.left, curr);                q.offer(curr.left);            }            if (curr.right != null) {                parents.put(curr.right, curr);                q.offer(curr.right);            }        }    }
    static int timeToBurn(TreeNode root, TreeNode target) {        Map<TreeNode, TreeNode> parents = new HashMap<>();        mapParents(root, parents);
        Queue<TreeNode> q = new LinkedList<>();        Set<TreeNode> visited = new HashSet<>();        q.offer(target);        visited.add(target);        int minutes = 0;
        while (!q.isEmpty()) {            int size = q.size();            boolean spread = false;            for (int i = 0; i < size; i++) {                TreeNode curr = q.poll();                TreeNode[] neighbors = {curr.left, curr.right, parents.get(curr)};                for (TreeNode next : neighbors) {                    if (next != null && !visited.contains(next)) {                        visited.add(next);                        q.offer(next);                        spread = true;                    }                }            }            if (spread) minutes++;        }        return minutes;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(1);        root.left = new TreeNode(2);        root.right = new TreeNode(3);        root.left.left = new TreeNode(4);
        System.out.println("Time to burn: " + timeToBurn(root, root.left.left));    }}
Output
Time to burn: 3

What this code does

  • Parent links are recorded in a map to allow bidirectional movement.
  • Breadth-first search burns adjacent left, right, and parent nodes each round.
  • The number of rounds required to burn every connected node gives total time.

The maximum width is the maximum span between non-null nodes at any level. Assign heap-style indexes to nodes. Root has index 0. Left child gets 2 * i + 1. Right child gets 2 * i + 2. Normalize indexes by subtracting the level minimum index to avoid integer overflow. The width of a level is the difference between last index and first index plus one.

Burning a tree simulates fire spreading outward from a target node. First build parent references with breadth-first search to allow upward traversal. Then start a multi-directional breadth-first search from the burning node. Each minute spreads fire to left child, right child, and parent simultaneously.

Choosing the optimal traversal pattern

Choosing the correct traversal simplifies code and minimizes auxiliary memory usage. Use breadth-first search for shortest paths, level views, and level widths.

Use preorder depth-first search when parents must precede children, such as cloning trees. Use inorder traversal for binary search trees to visit keys in ascending order.

Use postorder traversal when bottom-up values like heights and subtree sizes are required. Postorder guarantees both child subtrees finish before processing the parent node.

Finish up

Mark complete & continue

Next: The BST rule