Bird
Raised Fist0
DSA Javaprogramming~10 mins

Path Sum Root to Leaf in Binary Tree in DSA Java - Execution Trace

Choose your learning style10 modes available
Concept Flow - Path Sum Root to Leaf in Binary Tree
Start at root node
↓
Check if node is null?
Yes→Return false
No↓
Check if leaf node?
Yes→Check if sum equals target
↓
Return true/false
↓
Recurse left with updated sum
↓
Recurse right with updated sum
↓
Return left_result OR right_result
Start from root, check if node is leaf and sum matches target, else recurse left and right with updated sum, return true if any path matches.
Execution Sample
DSA Java
boolean hasPathSum(TreeNode node, int sum) {
  if (node == null) return false;
  if (node.left == null && node.right == null) return sum == node.val;
  return hasPathSum(node.left, sum - node.val) || hasPathSum(node.right, sum - node.val);
}
Checks if any root-to-leaf path sums to the target value.
Execution Table
StepOperationCurrent NodeSum RemainingReturn ValueVisual State
1Start at root522?5 / \ 4 8 / / \ 11 13 4 / \ 7 2 1
2Check leaf?522NoSame as above
3Recurse left417?4 / 11 / 7 2
4Check leaf?417NoSame as above
5Recurse left1113?11 / 7 2
6Check leaf?1113NoSame as above
7Recurse left72?7
8Check leaf?72Yes7
9Leaf node sum check72False7
10Recurse right22?2
11Check leaf?22Yes2
12Leaf node sum check22True2
13Return true up1113True11 subtree
14Return true up417True4 subtree
15Return true up522TrueWhole tree
💡 Returned true at leaf node with value 2 where remaining sum matched.
Variable Tracker
VariableStartAfter Step 3After Step 5After Step 7After Step 10Final
Current Node541172null
Sum Remaining22171322N/A
Return Value???FalseTrueTrue
Key Moments - 3 Insights
Why do we check if the node is a leaf before comparing sums?
Because only root-to-leaf paths count. See steps 2, 6, 8, 11 where leaf check happens before sum comparison.
Why do we subtract node value from sum when recursing?
We track remaining sum needed. At each step, sum reduces by current node's value (see 'Sum Remaining' column).
What happens if a subtree returns true?
The function returns true immediately up the call stack (steps 12-15), no need to check other paths.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the sum remaining when visiting node 11?
A13
B17
C2
D22
💡 Hint
Check the 'Sum Remaining' column at step 5.
At which step does the function first return true?
AStep 9
BStep 12
CStep 15
DStep 7
💡 Hint
Look at the 'Return Value' column for the first 'True' value.
If the leaf node with value 2 was changed to 3, what would happen at step 12?
AReturn true
BReturn false
CReturn null
DError
💡 Hint
Sum remaining at step 12 is 2, leaf value changed to 3, so sum == node.val check fails.
Concept Snapshot
Path Sum Root to Leaf in Binary Tree:
- Start at root, check if node is leaf
- If leaf, compare sum with node value
- Else recurse left and right with sum - node.val
- Return true if any path matches sum
- Returns false if no path matches
Full Transcript
This concept checks if there is a root-to-leaf path in a binary tree where the sum of node values equals a target sum. Starting at the root, we check if the node is null, returning false if so. If the node is a leaf, we compare the remaining sum with the node's value. If they match, we return true. Otherwise, we recursively check the left and right subtrees with the updated sum (original sum minus current node's value). The function returns true if any path matches the sum, or false if none do. The execution table traces each step, showing the current node, remaining sum, and return values. Key moments clarify why leaf checks happen first, why sum is updated, and how true returns propagate up the call stack.

Practice

(1/5)
1. What does the "Path Sum Root to Leaf" problem ask you to find in a binary tree?
easy
A. If there exists a root-to-leaf path with a sum equal to a given target
B. The maximum depth of the binary tree
C. The total number of leaf nodes in the tree
D. The sum of all node values in the tree

Solution

  1. Step 1: Understand the problem statement

    The problem asks if any path from the root node down to any leaf node sums exactly to a given target value.
  2. Step 2: Identify what is being checked

    We check if such a path exists, not the maximum depth or total sum of all nodes.
  3. Final Answer:

    If there exists a root-to-leaf path with a sum equal to a given target -> Option A
  4. Quick Check:

    Path sum check = existence of target sum path [OK]
Hint: Focus on root-to-leaf paths and their sums [OK]
Common Mistakes:
  • Confusing total tree sum with path sum
  • Checking any path, not root-to-leaf
  • Looking for maximum depth instead
2. Which of the following Java method signatures correctly represents a function to check path sum in a binary tree node class?
easy
A. public void hasPathSum(TreeNode root, int targetSum)
B. public int hasPathSum(TreeNode root, int targetSum)
C. public String hasPathSum(TreeNode root, int targetSum)
D. public boolean hasPathSum(TreeNode root, int targetSum)

Solution

  1. Step 1: Identify the return type for path sum check

    The function should return true or false, so the return type must be boolean.
  2. Step 2: Check method signature correctness

    public boolean hasPathSum(TreeNode root, int targetSum) returns boolean and takes root node and target sum as parameters, matching the problem requirements.
  3. Final Answer:

    public boolean hasPathSum(TreeNode root, int targetSum) -> Option D
  4. Quick Check:

    Return type boolean for true/false check [OK]
Hint: Return boolean for yes/no path sum check [OK]
Common Mistakes:
  • Using int or void return type instead of boolean
  • Returning String instead of boolean
  • Incorrect parameter types
3. What will be the output of the following code snippet?
class TreeNode {
  int val;
  TreeNode left, right;
  TreeNode(int val) { this.val = val; }
}

public class Solution {
  public boolean hasPathSum(TreeNode root, int targetSum) {
    if (root == null) return false;
    if (root.left == null && root.right == null) return root.val == targetSum;
    return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
  }

  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(7);
    root.left.left.right = new TreeNode(2);
    root.right.left = new TreeNode(13);
    root.right.right = new TreeNode(4);
    root.right.right.right = new TreeNode(1);

    Solution sol = new Solution();
    System.out.println(sol.hasPathSum(root, 22));
  }
}
medium
A. true
B. false
C. Compilation error
D. Runtime exception

Solution

  1. Step 1: Trace the path sums in the tree

    Check if any root-to-leaf path sums to 22. One path is 5->4->11->2 = 22.
  2. Step 2: Evaluate the recursive calls

    The function returns true because the path sum 22 exists, so it prints true.
  3. Final Answer:

    true -> Option A
  4. Quick Check:

    Path 5+4+11+2 = 22 exists [OK]
Hint: Look for any root-to-leaf path matching target sum [OK]
Common Mistakes:
  • Ignoring leaf node condition
  • Subtracting sum incorrectly
  • Assuming sum must be from root to any node
4. Identify the bug in the following code for checking path sum and select the correct fix:
public boolean hasPathSum(TreeNode root, int targetSum) {
  if (root == null) return false;
  if (root.left == null && root.right == null) return root.val == targetSum;
  return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);
}
medium
A. Change return type to int
B. Subtract root.val from targetSum in recursive calls
C. Check only left subtree for path sum
D. Return true if root is null

Solution

  1. Step 1: Analyze recursive call parameters

    The code calls hasPathSum with the same targetSum without subtracting root.val, so it doesn't reduce the sum along the path.
  2. Step 2: Correct the recursive calls

    Subtract root.val from targetSum in recursive calls to track remaining sum needed.
  3. Final Answer:

    Subtract root.val from targetSum in recursive calls -> Option B
  4. Quick Check:

    Update targetSum by subtracting node value [OK]
Hint: Always reduce targetSum by current node's value [OK]
Common Mistakes:
  • Not subtracting node value in recursion
  • Returning true on null node
  • Ignoring right subtree
5. Given a binary tree where node values can be negative, zero, or positive, which modification is necessary to correctly check for a path sum equal to a target value?
hard
A. Check for path sums only in positive-valued nodes
B. Use a global variable to track sums instead of recursion
C. No modification needed; standard path sum check works for all values
D. Modify the function to handle negative sums by not stopping at leaf nodes

Solution

  1. Step 1: Understand impact of negative values on path sum

    Negative values do not affect the logic; the sum is still accumulated along the path.
  2. Step 2: Confirm standard recursive approach works

    The standard recursive subtraction and leaf check works regardless of node values being negative, zero, or positive.
  3. Final Answer:

    No modification needed; standard path sum check works for all values -> Option C
  4. Quick Check:

    Standard method handles all integer values [OK]
Hint: Standard recursion handles negative values fine [OK]
Common Mistakes:
  • Thinking negative values break the logic
  • Trying to skip negative nodes
  • Changing leaf node condition unnecessarily
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard