Trees and tree words
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Trees organize data hierarchically, connecting nodes through parent and child relationships.
Core Terminology: Root, Leaves, Parents, and Children
A tree is a set of nodes connected by edges with one root at the top and no cycles; every node except the root has exactly one parent.
A tree is a non-linear data structure consisting of nodes connected by directed edges. The topmost node with no parent is called the root. Arrays and linked lists store items in sequential order; trees model natural hierarchies with branching relationships.
class TreeNode { int val; TreeNode left, right; // a binary tree node has at most two children TreeNode(int val) { this.val = val; }}TreeNode root = new TreeNode(10); // the root: no parentroot.left = new TreeNode(5); // 5 and 15 are children of 10root.right = new TreeNode(15); // and leaves: they have no childrenEvery node except the root has exactly one parent node above it. A node can have zero or more children below it. In a binary tree, each node has at most two children, called left and right. Nodes with zero children are called leaf nodes.
Trace a small tree with values 10, 5, and 15. Node 10 sits at the top as the root. Node 10 connects left to child 5 and right to child 15. Both 5 and 15 have zero children, making them leaf nodes. Nodes 5 and 15 share 10 as their common parent.
Tree Measurements: Height, Depth, and Levels
A binary tree is a tree in which every node has at most two children, called the left child and the right child.
The depth of a node counts the edges from the root down to it. The height of a node counts the edges on its longest path down to a leaf. The code below prints both for a small tree.
static int height(TreeNode node) { if (node == null) return -1; // empty tree: height -1, so a leaf gets 0 return 1 + Math.max(height(node.left), height(node.right));}
static int depth(TreeNode node, int target, int d) { // call with d = 0 at the root if (node == null) return -1; // target not found here if (node.val == target) return d; int left = depth(node.left, target, d + 1); return left != -1 ? left : depth(node.right, target, d + 1);}The depth of a node is the number of edges from the root down to that node. The height of a node is the number of edges on the longest path down to a leaf. The root always sits at depth 0, and all leaf nodes have a height of 0.
The level of a node is often defined as depth + 1. The height of the entire tree is the height of its root node. An empty tree has a height of -1, while a single-node tree has height 0. Trace measurements on a small three-node tree. Root 10 has depth 0 and height 2. Node 5 has depth 1 and height 1. Node 2 is a leaf with depth 2 and height 0. The entire tree has a height of 2.
Predict the output
Missing children are null
Read the code, then pick what it prints.
Round 1 of 2
TreeNode has val, left and right. Only the left child of the root is set.
Representing Trees in Java and Real-World Hierarchies
A binary tree is stored in Java as linked nodes. Each node holds a value and two references, left and right; a null reference means that child does not exist.
Example 1 · Building a Binary Tree Manually
public class BasicTreeDemo { static class TreeNode { int val; TreeNode left; TreeNode right;
TreeNode(int val) { this.val = val; } }
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("Root: " + root.val); System.out.println("Left child: " + root.left.val); System.out.println("Right child: " + root.right.val); System.out.println("Left-left leaf: " + root.left.left.val); }}Root: 1 Left child: 2 Right child: 3 Left-left leaf: 4
What this code does
- Creates TreeNode instances holding integer values and null child pointers.
- Manually assigns left and right pointers to establish parent-child links.
Example 2 · Counting Nodes in a Binary Tree
public class CountNodesDemo { static class TreeNode { int val; TreeNode left, right; TreeNode(int val) { this.val = val; } }
public static int countNodes(TreeNode root) { if (root == null) return 0; return 1 + countNodes(root.left) + countNodes(root.right); }
public static void main(String[] args) { TreeNode root = new TreeNode(10); root.left = new TreeNode(5); root.right = new TreeNode(20); root.left.right = new TreeNode(8);
System.out.println("Total nodes: " + countNodes(root)); }}Total nodes: 4
What this code does
- Base case returns 0 when encountering a null subtree pointer.
- Recursively adds 1 for the current node plus counts from both subtrees.
Example 3 · Counting Leaf Nodes
public class CountLeavesDemo { static class TreeNode { int val; TreeNode left, right; TreeNode(int val) { this.val = val; } }
public static int countLeaves(TreeNode root) { if (root == null) return 0; if (root.left == null && root.right == null) return 1; return countLeaves(root.left) + countLeaves(root.right); }
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); root.left.right = new TreeNode(5);
System.out.println("Leaf count: " + countLeaves(root)); }}Leaf count: 3
What this code does
- Identifies a leaf when both left and right pointers are null.
- Sums leaf counts from left and right subtrees recursively.
In Java, we represent a binary tree node using a class with two reference pointers. The TreeNode class holds a data value and references to left and right child nodes. If a child does not exist, its pointer is null. A tree is referenced simply by holding a pointer to its root node.
Hierarchical trees model numerous everyday computing systems. Your operating system file system stores nested directories as a multi-way tree. Web browsers parse HTML documents into the Document Object Model tree. Corporate management structures and taxonomy classification systems also form trees. When building trees in code, watch out for edge cases. An empty tree is represented simply by a null root pointer. A skewed tree where every node has only one child degenerates into a linked list. Algorithms on degenerate trees take linear O(n) time instead of logarithmic O(log n).
Next step
Check your understanding
10 quick questions