Skip to lesson

A tree path is a sequence of connected nodes. Exploring paths helps us find target sums and tree costs.

Root-to-leaf paths and path sums

A root-to-leaf path is a sequence of nodes that starts at the root and ends at a leaf, a node with no children.

A root-to-leaf path begins at the root and finishes at a node with no children. A naive brute-force approach collects every path into lists and checks sums later. That uses extra memory. A better way tracks a running sum during depth-first search.

Example 1 · Root to Leaf Path Collector

Main.javaJava
import java.util.ArrayList;import java.util.List;
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static void findPaths(TreeNode node, List<Integer> current, List<String> result) {        if (node == null) return;        current.add(node.val);        if (node.left == null && node.right == null) {            StringBuilder sb = new StringBuilder();            for (int i = 0; i < current.size(); i++) {                if (i > 0) sb.append("->");                sb.append(current.get(i));            }            result.add(sb.toString());        } else {            findPaths(node.left, current, result);            findPaths(node.right, current, result);        }        current.remove(current.size() - 1);    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(1);        root.left = new TreeNode(2);        root.right = new TreeNode(3);        root.left.right = new TreeNode(5);
        List<String> paths = new ArrayList<>();        findPaths(root, new ArrayList<>(), paths);        for (String p : paths) {            System.out.println(p);        }    }}
Output
1->2->5
1->3

What this code does

  • The helper method adds the current node value to a dynamic list.
  • Leaf nodes convert the accumulated list into an arrow separated string.
  • Backtracking removes the last element after child calls finish.

Example 2 · Brute force: collect every path, then add each one (O(n·h) time and space)

PathSumBruteDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class PathSumBruteDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int v) { val = v; }    }
    static void collect(TreeNode node, List<Integer> current, List<List<Integer>> all) {        if (node == null) return;        current.add(node.val);        if (node.left == null && node.right == null) {            all.add(new ArrayList<>(current));        } else {            collect(node.left, current, all);            collect(node.right, current, all);        }        current.remove(current.size() - 1);    }
    static boolean hasPathSum(TreeNode root, int target) {        List<List<Integer>> all = new ArrayList<>();        collect(root, new ArrayList<>(), all);        for (List<Integer> path : all) {            int sum = 0;            for (int value : path) sum += value;            if (sum == target) return true;        }        return false;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(5);        root.left = new TreeNode(4);        root.right = new TreeNode(8);        root.left.left = new TreeNode(11);        root.left.left.left = new TreeNode(2);
        System.out.println("Sum 22 exists: " + hasPathSum(root, 22));        System.out.println("Sum 15 exists: " + hasPathSum(root, 15));    }}
Output
Sum 22 exists: true
Sum 15 exists: false

What this code does

  • Every complete root-to-leaf path is copied into its own list, and only afterwards is each list added up.
  • The copies take up to O(n·h) memory, and every value is added again for each path that contains it.

Example 3 · Optimal: subtract on the way down (O(n) time, O(h) space)

Main.javaJava
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static boolean hasPathSum(TreeNode root, int target) {        if (root == null) return false;        if (root.left == null && root.right == null) {            return target == root.val;        }        int remaining = target - root.val;        return hasPathSum(root.left, remaining) || hasPathSum(root.right, remaining);    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(5);        root.left = new TreeNode(4);        root.right = new TreeNode(8);        root.left.left = new TreeNode(11);        root.left.left.left = new TreeNode(2);
        System.out.println("Sum 22 exists: " + hasPathSum(root, 22));        System.out.println("Sum 15 exists: " + hasPathSum(root, 15));    }}
Output
Sum 22 exists: true
Sum 15 exists: false

What this code does

  • Each recursive step subtracts the current node value from the target.
  • A leaf node checks whether its value equals the remaining target.
  • The method returns true if either child subtree contains the target.
  • Why it is faster: the remaining target travels down as a number, so nothing is copied or added twice, and each node is visited once.

Trace a tree with root 5 having children 4 and 8. The left child 4 has child 11. Start at root 5 with target sum 20. Subtract 5 to get remaining sum 15. Move left to 4 and subtract 4 to get 11. Move to 11 and subtract 11 to get 0. Because node 11 is a leaf and remaining sum is 0, the path exists. Always check both left and right children before declaring a leaf. A node with one child is not a leaf.

Maximum path sum across any nodes

A path may start and end at any node but cannot branch. Each node returns its best downward branch, and the best path through a node is its value plus both branch gains.

Example 4 · Maximum Path Sum

Main.javaJava
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static int maxSum = Integer.MIN_VALUE;
    static int maxGain(TreeNode node) {        if (node == null) return 0;        int leftGain = Math.max(0, maxGain(node.left));        int rightGain = Math.max(0, maxGain(node.right));
        int priceNewPath = node.val + leftGain + rightGain;        maxSum = Math.max(maxSum, priceNewPath);
        return node.val + Math.max(leftGain, rightGain);    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(-10);        root.left = new TreeNode(9);        root.right = new TreeNode(20);        root.right.left = new TreeNode(15);        root.right.right = new TreeNode(7);
        maxGain(root);        System.out.println("Maximum path sum: " + maxSum);    }}
Output
Maximum path sum: 42

What this code does

  • Negative subtree sums are ignored by taking Math.max with zero.
  • The global maximum updates with the sum through the current root.
  • The function returns the maximum single branch sum to the parent.

Some problems allow paths to start and end at any node. The path cannot split into multiple branches. A brute-force check tests paths between every pair of nodes. That takes quadratic time on balanced trees. We can solve this in linear time using a bottom-up postorder traversal.

Consider node values [-10, 9, 20, null, null, 15, 7]. Here 20 has children 15 and 7. For each node, compute the best single branch sum extending downward. If a child branch sum is negative, drop it by taking the maximum with zero. At node 20, the left branch gives 15 and the right branch gives 7. The combined path through node 20 is 20 + 15 + 7 = 42. Node 20 returns 20 + max(15, 7) = 35 up to its parent -10.

Passing values down versus returning values up

Top-down recursion passes values down as method arguments. Bottom-up recursion computes results from subtrees and returns them up.

Java
// Top-down: the running sum travels DOWN as an argumentstatic void printPathSums(TreeNode node, int sumSoFar) {    if (node == null) return;    sumSoFar += node.val;    if (node.left == null && node.right == null) System.out.println(sumSoFar);    printPathSums(node.left, sumSoFar);    printPathSums(node.right, sumSoFar);}// Bottom-up: each subtree's sum comes UP as a return valuestatic int subtreeSum(TreeNode node) {    if (node == null) return 0;    return node.val + subtreeSum(node.left) + subtreeSum(node.right);}

Running path sums and accumulated lists use the top-down style. Each recursive call receives state from its ancestor. Backtracking removes the current node when returning. Subtree heights and branch sums use the bottom-up style. The parent node combines results returned by its left and right children.

Choose top-down when a path property depends on ancestors. Choose bottom-up when decisions depend on descendants.

Next step

Check your understanding

10 quick questions