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.
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]null
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
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 leftleftleftnullbuildshow
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)preorderpreordernull
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.
- 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 ArrayDequejava.utiladdpoll
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][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.
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 heightlevelOrdersearchPathinsertbuildshow
The main
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:
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][1, 3, 4, 5, 8, 9][1, 4, 3, 9, 8, 5][[5], [3, 8], [1, 4, 9]][5, 3, 4] found[5, 8] not found
Every method checks for null[][7][1, null, 3, null, 4, null, 5, null, 8, null, 9]null
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
does.height - 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
does.searchPath
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()sizequeue.size()
Checking a BST against the children alone
Is [5, 3, 8, 1, 6, null, 9]
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:
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]][[5], [3, 8], [1, 4, 9]]truefalse
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
Maximum Depth of Binary Tree counts the nodes on the longest path down from the root, one more than the height in edges used here.Diameter of Binary Tree uses both subtree heights at every node to find the longest path.Balanced Binary Tree checks the balanced rule from the heights in a single walk.Invert Binary Tree mirrors both subtrees first, then swaps them at the node.
Preorder: pass a value down
Path Sum carries the running sum from the root to each leaf.Count Good Nodes in Binary Tree carries the largest value seen so far.
Level order with a queue
Binary Tree Level Order Traversal is the queue walk as a problem of its own.Binary Tree Right Side View keeps the last node of each round.
Binary search trees
Kth Smallest Element in a BST stops an inorder walk partway, since inorder gives sorted values, and keeps the waiting nodes on a stack instead of in calls.Lowest Common Ancestor of a BST walks down one path by comparing, like the search for 4.