Binary Tree Algorithms
Binary Trees: Complete Study Notes
Introduction to Trees and Binary Trees
A tree is a data structure consisting of nodes (typically drawn as circles) connected by edges (lines or arrows). Nodes may contain values of any type — integers, characters, objects, etc. Trees are often described using familial relationships: a node can be a parent (pointing to other nodes) or a child (pointed to by another node). The root is the node with no parent (no incoming edges). A leaf is a node with no children (no outgoing edges). Leaves can occur at different depths.
A binary tree is a tree where every node has at most two children. The two children are typically referred to as the left child and right child. This is a stricter form of a general tree.
Definition: A binary tree is a tree satisfying three criteria:
Every node has at most 2 children.
There is exactly one root (one node with no parent).
There is exactly one path between the root and any node (no cycles).
If any of these criteria are violated, the structure is not a binary tree. For example, if a node has three children, it's a ternary tree, not binary. If there are two nodes with no parent, there is no single root. If there is a cycle, there are multiple paths from root to a node.
Edge cases:
A binary tree can have a root with only one child — still a binary tree.
A singleton tree (one node) is a binary tree.
An empty tree (zero nodes) is also considered a binary tree — useful as a base case in algorithms.
Identifying binary trees in unusual shapes: A tree may be drawn non-traditionally (e.g., not top-down) but still satisfy all three criteria. It is still a binary tree; the relationships matter, not the visual arrangement.
Binary trees appear frequently in technical interviews and real-world software development. Understanding their definitions and traversal algorithms is essential.
Representing Binary Trees Programmatically
Binary trees are typically implemented using objects (instances of a class) in most programming languages. Each node object stores:
value(orval): the data stored at the node.left: pointer/reference to the left child (set tonull/Noneif absent).right: pointer/reference to the right child (set tonull/Noneif absent).
Example in JavaScript (class syntax):
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}To create a binary tree, instantiate nodes and wire them manually:
const a = new Node('a');
const b = new Node('b');
const c = new Node('c');
const d = new Node('d');
const e = new Node('e');
const f = new Node('f');
a.left = b;
a.right = c;
b.left = d;
b.right = e;
c.right = f;This creates a tree with root a, left child b (with children d, e), right child c (with right child f). The null children are implicit (e.g., c.left is null).
This static manual construction is used for learning and testing; real applications generate trees dynamically.
Depth‑First Traversal
Depth‑first traversal (DFT) visits nodes by going as deep as possible along each branch before moving laterally. The order is: root, then left subtree (fully), then right subtree (fully). This is equivalent to preorder traversal (root, left, right).
Data structure: A stack (Last In, First Out). Explicit stack for iterative version; recursive solution uses the call stack.
Algorithm (iterative):
Initialize a stack with the root node.
While stack is not empty:
Pop the top element (current node).
Process the node (e.g., add its value to result list).
If the node has a right child, push it onto stack.
If the node has a left child, push it onto stack. (Order of pushing children determines traversal direction: pushing left then right gives right-to-left; pushing right then left gives left-to-right.)
Return result list.
Example trace (left-to-right): Starting with root a, stack: [a]. Pop a, process. Push right child c, then left child b → stack: [c, b]. Pop b, process. Push e, then d → stack: [c, e, d]. Pop d, process. Pop e, process. Pop c, process. Push f → stack: [f]. Pop f, process. Result: a, b, d, e, c, f.
Complexity:
Time: O(n), where n is number of nodes — each node is visited once.
Space: O(n) in worst case (stack size) for iterative; also O(n) for recursive call stack.
Recursive implementation (depth‑first, left-to-right):
const depthFirstValues = (root) => {
if (root === null) return [];
const leftValues = depthFirstValues(root.left);
const rightValues = depthFirstValues(root.right);
return [root.val, ...leftValues, ...rightValues];
};This uses the call stack implicitly. The base case for empty (null) tree returns an empty array. For a non‑null node, recursively get left values, then right values, and combine with current value.
Important: The recursive approach gives a preorder traversal (root, left, right). It is naturally depth‑first because recursion uses a stack.
Breadth‑First Traversal
Breadth‑first traversal (BFT) visits nodes level by level, from left to right. It goes across the tree before going deeper. Order: root, then all nodes at depth 1, then all nodes at depth 2, etc.
Data structure: A queue (First In, First Out). Not naturally recursive; implement iteratively.
Algorithm:
Initialize a queue with the root node.
While queue is not empty:
Dequeue the front element (current node).
Process the node (add its value to result).
If current node has a left child, enqueue it.
If current node has a right child, enqueue it.
Return result list.
Example trace: Start with queue [a]. Dequeue a, process. Enqueue b, c → queue: [b, c]. Dequeue b, process. Enqueue d, e → queue: [c, d, e]. Dequeue c, process. Enqueue f → queue: [d, e, f]. Dequeue d, process. Dequeue e, process. Dequeue f, process. Result: a, b, c, d, e, f.
Complexity:
Time: O(n) — each node enqueued/dequeued once, assuming O(1) queue operations. (If using JavaScript array
.shift(), it's O(n) per shift, giving O(n2) worst-case.)Space: O(n) for queue.
Code implementation (breadth‑first):
const breadthFirstValues = (root) => {
if (root === null) return [];
const queue = [root];
const values = [];
while (queue.length > 0) {
const current = queue.shift();
values.push(current.val);
if (current.left) queue.push(current.left);
if (current.right) queue.push(current.right);
}
return values;
};Key difference from depth‑first: Use .shift() (or efficient deque) to remove from front, and .push() to add to back.
Breadth‑first cannot be easily implemented recursively because recursion inherently uses a stack, not a queue.
Problem: Tree Includes
Goal: Given a binary tree and a target value, return true if the target exists in the tree, false otherwise.
Approaches:
Breadth‑first search (BFS): Traverse level by level using a queue, checking each node's value. Return
trueimmediately upon match. If queue empties without match, returnfalse.Depth‑first search (DFS) iterative: Use a stack, similar logic.
Depth‑first recursive: A clean recursive solution.
Recursive DFS solution:
const treeIncludes = (root, target) => {
if (root === null) return false;
if (root.val === target) return true;
return treeIncludes(root.left, target) || treeIncludes(root.right, target);
};Base cases: if root is null (empty subtree), return false; if current node's value equals target, return true. Otherwise, recursively search left and right subtrees using logical OR — return true if found in either.
Complexity: Both time and space O(n).
Important edge case: Empty tree (root === null) should immediately return false.
Problem: Tree Sum
Goal: Given a binary tree with numeric values, compute the total sum of all node values.
Approaches:
Iterative (breadth‑first or depth‑first): Traverse tree, maintain a running sum.
Recursive (depth‑first): Elegant and succinct.
Recursive solution:
const treeSum = (root) => {
if (root === null) return 0;
return root.val + treeSum(root.left) + treeSum(root.right);
};Base case: empty tree returns 0. For a non‑null node, sum = current value + sum of left subtree + sum of right subtree.
Complexity: O(n) time, O(n) space (call stack).
Iterative (breadth‑first) solution:
const treeSum = (root) => {
if (root === null) return 0;
const queue = [root];
let total = 0;
while (queue.length > 0) {
const current = queue.shift();
total += current.val;
if (current.left) queue.push(current.left);
if (current.right) queue.push(current.right);
}
return total;
};Processing logic occurs when a node leaves the queue — this is cleaner than adding child values upon enqueue.
Problem: Tree Min Value
Goal: Given a non‑empty binary tree with numeric values, find the minimum value. Assume tree has at least one node.
Approaches:
Iterative (breadth‑first or depth‑first): Traverse, maintain
smallestvariable initialized toInfinity. Update when smaller value found.Recursive depth‑first: Combine recursion with comparison.
Recursive solution:
const treeMinValue = (root) => {
if (root === null) return Infinity;
const leftMin = treeMinValue(root.left);
const rightMin = treeMinValue(root.right);
return Math.min(root.val, leftMin, rightMin);
};Base case: null node returns Infinity (so it never wins a min comparison). For a non‑null node, find the minimum among current value, minimum of left subtree, and minimum of right subtree.
Complexity: O(n) time, O(n) space.
Iterative (depth‑first) solution:
const treeMinValue = (root) => {
const stack = [root];
let smallest = Infinity;
while (stack.length > 0) {
const current = stack.pop();
if (current.val < smallest) smallest = current.val;
if (current.left) stack.push(current.left);
if (current.right) stack.push(current.right);
}
return smallest;
};Initialize smallest to Infinity because any actual value will be less.
Problem: Max Root‑to‑Leaf Path Sum
Goal: Given a binary tree with numeric values, find the maximum sum along any path from the root to a leaf. A leaf is a node with no children.
Approach: Recursive depth‑first.
Key idea: At each node, compute the maximum path sum to a leaf in its left and right subtrees. Return the current node's value plus the larger of those two values. Base cases handle null nodes and leaf nodes.
Base cases:
If node is
null(empty child of a non‑leaf node): return-Infinity(or a very small number) so it never wins amaxcomparison.If node is a leaf (no left and no right child): return
node.val(the sum of just this node).
Recursive solution:
const maxPathSum = (root) => {
if (root === null) return -Infinity;
if (root.left === null && root.right === null) return root.val;
const maxChildPathSum = Math.max(maxPathSum(root.left), maxPathSum(root.right));
return root.val + maxChildPathSum;
};Explanation: For a null node, -Infinity ensures it won't be chosen. For a leaf, the sum is just its value. For an internal node, find the maximum path sum from its children (the better continuation) and add its own value.
Complexity: O(n) time (each node visited once), O(n) space (call stack).
Example: Tree with root 5, left subtree 11 (with leaves 4 and 2), right subtree 3 (with right leaf 1). Paths: 5+11+4=20, 5+11+2=18, 5+3+1=9. Maximum is 20.
Summary of Recursive Patterns for Binary Trees
Many binary tree problems share a common recursive structure:
Base case: Usually the empty tree (
null) returns a neutral value (0 for sum,Infinityfor min,-Infinityfor max,falsefor includes).Recursive case: Solve left and right subtrees, then combine results with current node's value.
Combining operations:
Sum:
root.val + left + rightMin:
Math.min(root.val, leftMin, rightMin)Max root‑to‑leaf sum:
root.val + Math.max(leftMax, rightMax)(with leaf base case)Includes:
root.val === target || leftResult || rightResult
Depth‑first traversal (recursive) is often the cleanest for problems requiring path‑awareness or per‑node decisions. Breadth‑first (iterative) is best when order at each level matters (e.g., level‑order printing).
These fundamental patterns form the basis for solving more complex binary tree problems in interviews and real‑world applications.

Ask anything
We've read this whole study set, so questions about it get the best answers.