Bird
Raised Fist0
DSA Javascriptprogramming~10 mins

Path Sum Root to Leaf in Binary Tree in DSA Javascript - 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 Javascript
function hasPathSum(node, sum) {
  if (!node) return false;
  if (!node.left && !node.right) 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 Tree State
1Start at root522?5 / \ 4 8 / / \ 11 13 4 / \ 7 2 1
2Check leaf?522NoSame
3Recurse left417?Same
4Check leaf?417NoSame
5Recurse left1113?Same
6Check leaf?1113NoSame
7Recurse left72?Same
8Check leaf?72YesSame
9Compare sum72FalseSame
10Recurse right22?Same
11Check leaf?22YesSame
12Compare sum22TrueSame
13Return true up1113TrueSame
14Return true up417TrueSame
15Return true up522TrueSame
16StopN/AN/ATrueFinal: Path 5->4->11->2 sums to 22
💡 Found a root-to-leaf path with sum 22, so returns true.
Variable Tracker
VariableStartAfter Step 3After Step 5After Step 7After Step 10Final
node541172N/A
sum_remaining22171322N/A
return_value?????True
Key Moments - 3 Insights
Why do we check if the node is a leaf before comparing sums?
Because only root-to-leaf paths count. The check at step 8 and 11 ensures we only compare sums when at a leaf node, as shown in execution_table rows 8-12.
Why do we subtract node.val from sum when recursing?
We reduce the target sum by the current node's value to track how much is left to reach the target. This is seen in the sum_remaining column updating at steps 3, 5, 7, and 10.
What happens if the node is null?
The function returns false immediately (step 2), meaning no path exists through a null node.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 11, what is the sum_remaining value?
A13
B17
C2
D22
💡 Hint
Check the 'Sum Remaining' column at step 11 in the execution_table.
At which step does the function find a valid path sum and return true?
AStep 12
BStep 14
CStep 9
DStep 16
💡 Hint
Look for the first 'Compare sum' operation returning true in the execution_table.
If the target sum was 26 instead of 22, what would happen at step 12?
AReturn true because sum matches
BReturn false because sum does not match
CRecurse further left
DReturn false because node is null
💡 Hint
At step 12, the sum comparison depends on sum_remaining matching node.val exactly.
Concept Snapshot
function hasPathSum(node, sum)
- Return false if node is null
- If leaf node, check sum === node.val
- Else recurse left and right with sum - node.val
- Return true if any path matches
- Finds if root-to-leaf path sums to target
Full Transcript
This visualization shows how the path sum check works in a binary tree. Starting at the root, the function checks if the node is null, returning false if so. If the node is a leaf, it compares the remaining sum to the node's value. If they match, it returns true. Otherwise, it recurses down left and right children, subtracting the current node's value from the sum. The execution table traces each step, showing the current node, remaining sum, and return values. The variable tracker shows how node and sum_remaining change. Key moments clarify why leaf checks and sum subtraction are needed. The quiz tests understanding of sum tracking and return points. This method efficiently finds if any root-to-leaf path equals the target sum.

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 nodes in the binary tree
D. The sum of all node values in the binary tree

Solution

  1. Step 1: Understand the problem statement

    The problem asks if there is any path from the root node down to any leaf node where the sum of the node values equals a given target sum.
  2. Step 2: Differentiate from other tree properties

    This is different from finding depth, counting nodes, or summing all nodes. It specifically checks for a path sum from root to leaf.
  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 problem = Check root-to-leaf sum [OK]
Hint: Focus on root-to-leaf paths, not entire tree sums [OK]
Common Mistakes:
  • Confusing path sum with total tree sum
  • Checking any path, not root-to-leaf
  • Ignoring leaf node condition
2. Which of the following is the correct base case check in JavaScript for a null node in a recursive path sum function?
easy
A. if (node === null) return true;
B. if (node == undefined) return true;
C. if (node === undefined) return null;
D. if (node === null) return false;

Solution

  1. Step 1: Identify base case for recursion

    When the current node is null, it means no path exists here, so return false to indicate failure to find the path.
  2. Step 2: Check JavaScript strict equality and return value

    Using 'node === null' is correct to check null nodes, and returning false means no valid path found.
  3. Final Answer:

    if (node === null) return false; -> Option D
  4. Quick Check:

    Null node means no path = false [OK]
Hint: Return false on null node to stop recursion [OK]
Common Mistakes:
  • Returning true on null node
  • Using == instead of ===
  • Returning null instead of boolean
3. What will be the output of the following code snippet?
class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function hasPathSum(node, sum) {
  if (node === null) return false;
  if (!node.left && !node.right) return sum === node.val;
  return hasPathSum(node.left, sum - node.val) || hasPathSum(node.right, sum - node.val);
}

const root = new TreeNode(5, new TreeNode(4, new TreeNode(11, new TreeNode(7), new TreeNode(2))), new TreeNode(8, null, new TreeNode(4, null, new TreeNode(1))));
console.log(hasPathSum(root, 22));
medium
A. true
B. false
C. undefined
D. TypeError

Solution

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

    Check if any root-to-leaf path sums to 22. The path 5->4->11->2 sums to 22 (5+4+11+2=22).
  2. Step 2: Evaluate the recursive calls

    The function returns true because the path exists, so console.log prints true.
  3. Final Answer:

    true -> Option A
  4. Quick Check:

    Path 5-4-11-2 sum=22 = true [OK]
Hint: Check leaf paths sums carefully to confirm true [OK]
Common Mistakes:
  • Ignoring leaf node condition
  • Miscomputing sum along path
  • Assuming false when path exists
4. Find the bug in this JavaScript function for path sum and select the fix:
function hasPathSum(node, sum) {
  if (node === null) return false;
  if (!node.left && !node.right) return sum = node.val;
  return hasPathSum(node.left, sum - node.val) || hasPathSum(node.right, sum - node.val);
}
medium
A. Change 'node === null' to 'node == null' in base case
B. Remove the leaf node check entirely
C. Change 'sum = node.val' to 'sum === node.val' in the leaf check
D. Change '||' to '&&' in the return statement

Solution

  1. Step 1: Identify incorrect assignment in leaf check

    The line 'return sum = node.val;' uses assignment '=' instead of comparison '===' which causes wrong behavior.
  2. Step 2: Correct the comparison operator

    Replace '=' with '===' to properly check if sum equals node.val at leaf nodes.
  3. Final Answer:

    Change 'sum = node.val' to 'sum === node.val' in the leaf check -> Option C
  4. Quick Check:

    Use '===' for comparison, not '=' [OK]
Hint: Use '===' for equality checks, not '=' assignment [OK]
Common Mistakes:
  • Using '=' instead of '===' in conditions
  • Removing necessary base cases
  • Changing logical operators incorrectly
5. Given a binary tree where node values can be negative, which modification is necessary to correctly check for a path sum equal to target?
function hasPathSum(node, sum) {
  if (node === null) return false;
  if (!node.left && !node.right) return sum === node.val;
  return hasPathSum(node.left, sum - node.val) || hasPathSum(node.right, sum - node.val);
}
hard
A. Use absolute values of node.val and sum in comparisons
B. No change needed; current code works with negative values
C. Change base case to return true if sum <= node.val
D. Add a visited set to avoid infinite loops with negative values

Solution

  1. Step 1: Understand negative values impact

    The current recursive approach subtracts node values from sum and checks leaf equality, which works even if values are negative.
  2. Step 2: Confirm no cycles in binary tree

    Binary trees have no cycles, so no infinite loops occur; no visited set needed.
  3. Final Answer:

    No change needed; current code works with negative values -> Option B
  4. Quick Check:

    Negative values handled by subtraction correctly [OK]
Hint: Binary trees have no cycles; negative values handled naturally [OK]
Common Mistakes:
  • Adding unnecessary visited sets
  • Changing base case incorrectly
  • Using absolute values which breaks logic
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