Knowledge Guide
HomeDSATrees

Introduction to Tree Depth First Search Pattern

The Tree Depth-First Search (DFS) traversal is a key technique in binary tree operations. It focuses on exploring one branch of the tree as far as possible before backtracking. This approach is useful for problems requiring tree traversal or handling hierarchical data.

The main types of DFS traversals include:

These techniques we have already discussed in the introduction chapter.

To solve DFS-based problems, the approach generally involves:

DFS is ideal for scenarios where exploring entire paths or working with node relationships is essential.

Let's understand the Tree DFS (Depth-First Search) traversal via the below problem.

Problem Statement

Given the root of a binary tree, explore all possible root-to-leaf paths, compute the sum of values along each path, and return the minimum sum.

A leaf node is a node with no children.

Examples

Example 1:

Image
Image

Example 2:

Image
Image

Example 3:

Image
Image

Solution

The algorithm calculates the minimum root-to-leaf path sum in a binary tree using a recursive approach. Starting at the root, it recursively explores the left and right subtrees, computes the minimum sum for each subtree, and adds the current node's value to the smaller of the two sums.

The base case is when the node is null, in which case the function returns 0. The recursion proceeds until it reaches the leaf nodes, and the minimum of the left and right sums is computed as it go back to the parent node of the particular node in the tree.

Step-by-Step Algorithm

  1. Base Case for Null Nodes:

    • If the current node (root) is null, return Integer.MAX_VALUE. This ensures that we do not consider non-existent paths while calculating the minimum sum.
  2. Base Case for Leaf Nodes:

    • If the current node is a leaf node (i.e., both left and right children are null), return the current node’s value (root.val) as a minimum sum. A leaf node is the endpoint of a valid path.
  3. Recursive Case for Non-leaf Nodes:

    • Step 3.1: Recursively compute the minimum sum for the left subtree by calling the same function on root.left.
    • Step 3.2: Recursively compute the minimum sum for the right subtree by calling the same function on root.right.
  4. Minimum Sum Calculation:

    • After computing the minimum sums for both the left and right subtrees, take the smaller of the two values using min(leftSum, rightSum).
  5. Add Current Node's Value:

    • Add the current node's value to the minimum of the left and right subtree sums.
  6. Return the Result:

    • Return the computed minimum root-to-leaf sum for the current node.

Algorithm Walkthrough

Image
Image

Step 1: Start at the root node (-1)

Step 2: Traverse the left subtree of node (-1) (node 2)

Step 3: Traverse the left child of node 2 (node 4)

Step 4: Traverse the right child of node 2 (node 5)

Step 5: Calculate the minimum sum for node 2

Step 6: Traverse the right subtree of node (-1) (node 3)

Step 7: Traverse the left child of node 3 (node 1)

Step 8: Calculate the minimum sum for node 3

Step 9: Calculate the minimum sum for the root node (-1)

Final Result:

The minimum root-to-leaf path sum for the given tree is 3, following the path -1 -> 3 -> 1.

Code

java
// class TreeNode {
//     int val;
//     TreeNode left;
//     TreeNode right;

//     // Constructor
//     TreeNode(int val) {
//         this.val = val;
//         left = null;
//         right = null;
//     }
// }

public class Solution {

  // Main function to return the minimum root to leaf sum
  public int minRootToLeafSum(TreeNode root) {
    // Base case: if the tree is empty, return a large value since we are finding the minimum sum
    if (root == null) {
      return Integer.MAX_VALUE;
    }

    // Base case: if we reached a leaf node, return its value
    if (root.left == null && root.right == null) {
      return root.val;
    }

    // Recursive case: compute the minimum sum for left and right subtrees
    int leftSum = minRootToLeafSum(root.left);
    int rightSum = minRootToLeafSum(root.right);

    // Return the minimum of the two sums, adding the current node's value
    return root.val + Math.min(leftSum, rightSum);
  }

  public static void main(String[] args) {
    // Example 1: Create the tree manually
    TreeNode root1 = new TreeNode(10);
    root1.left = new TreeNode(5);
    root1.right = new TreeNode(15);
    root1.right.left = new TreeNode(7);
    root1.right.right = new TreeNode(20);

    // Example 2: Create another tree
    TreeNode root2 = new TreeNode(-1);
    root2.left = new TreeNode(2);
    root2.right = new TreeNode(3);
    root2.left.left = new TreeNode(4);
    root2.left.right = new TreeNode(5);
    root2.right.left = new TreeNode(1);

    // Example 3: Create a third tree
    TreeNode root3 = new TreeNode(8);
    root3.left = new TreeNode(40);
    root3.right = new TreeNode(12);
    root3.right.left = new TreeNode(10);
    root3.right.right = new TreeNode(18);
    root3.right.left.left = new TreeNode(2);

    Solution solution = new Solution();

    // Print results for each example
    System.out.println(
      "Minimum Root to Leaf Path Sum (Example 1): " +
      solution.minRootToLeafSum(root1)
    ); // Output: 15
    System.out.println(
      "Minimum Root to Leaf Path Sum (Example 2): " +
      solution.minRootToLeafSum(root2)
    ); // Output: 3
    System.out.println(
      "Minimum Root to Leaf Path Sum (Example 3): " +
      solution.minRootToLeafSum(root3)
    ); // Output: 32
  }
}

Complexity Analysis

Time Complexity

The time complexity of this solution is , where N is the number of nodes in the binary tree. This is because the algorithm visits every node exactly once, performing constant-time work at each node (i.e., calculating the minimum of the left and right subtrees).

Space Complexity

The space complexity is determined by the recursion stack.

In the worst case (for example, a completely unbalanced tree), the space complexity can be , as the recursion stack may need to go as deep as the height of the tree, which could be N in the case of a skewed tree.

In the best case (a balanced binary tree), the space complexity is , where the maximum depth of recursion would be the height of the tree, which is log N for a balanced tree.

Now, let's start solving the problem on Tree DFS Pattern.

🤖 Don't fully get this? Learn it with Claude

Stuck on Introduction to Tree Depth First Search Pattern? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Introduction to Tree Depth First Search Pattern** (DSA) and want to truly understand it. Explain Introduction to Tree Depth First Search Pattern from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Introduction to Tree Depth First Search Pattern** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Introduction to Tree Depth First Search Pattern** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Introduction to Tree Depth First Search Pattern** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes