Bird
Raised Fist0
DSA Goprogramming~10 mins

Path Sum Root to Leaf in Binary Tree in DSA Go - 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 leaf
↓
Check if sum == node.Val
↓
Go to right child
↓
Return True
↓
Return False if no path found
Start from the root, check if current node is a leaf and if the remaining sum equals node's value. If yes, path found. Otherwise, recursively check left and right children with updated sum.
Execution Sample
DSA Go
func hasPathSum(root *TreeNode, sum int) bool {
  if root == nil {
    return false
  }
  if root.Left == nil && root.Right == nil {
    return sum == root.Val
  }
  return hasPathSum(root.Left, sum-root.Val) || hasPathSum(root.Right, sum-root.Val)
}
Checks if there is a root-to-leaf path in the binary tree where the sum of node values equals the target sum.
Execution Table
StepOperationCurrent Node ValueRemaining SumActionVisual State
1Start at root522Check leaf? No, go left5 / \ 4 8
2Go left417Check leaf? No, go left5 / \ 4 8 / / \ 11 13 4
3Go left1113Check leaf? No, go left5 / \ 4 8 / / \ 11 13 4 / \ 7 2
4Go left72Check leaf? Yes, sum==val? NoLeaf 7 checked, no match
5Back to 11, go right22Check leaf? Yes, sum==val? YesLeaf 2 checked, match found
6Return True--Path found: 5->4->11->2Path sum 22 found
7Stop--No further checks neededFinal result: True
💡 Found leaf node with remaining sum equal to node value, path sum exists.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4After Step 5Final
Current Noderoot(5)41172--
Remaining Sum22171322--
Path Foundfalsefalsefalsefalsetruetruetrue
Key Moments - 3 Insights
Why do we check if the node is a leaf before comparing sums?
Because only root-to-leaf paths count. As shown in step 4 and 5, we only compare sum when at a leaf node (no children).
What happens if the tree is empty (root is nil)?
The function returns false immediately (step 1), since no path exists in an empty tree.
Why do we subtract the current node's value from the sum when going deeper?
Because we want to check if the remaining sum matches the path ahead. This is shown in the 'Remaining Sum' column updating each step.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the remaining sum when the node with value 11 is visited?
A13
B17
C2
D22
💡 Hint
Check the 'Remaining Sum' column at Step 3 in the execution table.
At which step does the function find a matching path sum?
AStep 4
BStep 5
CStep 3
DStep 2
💡 Hint
Look for the step where 'sum==val? Yes' appears in the 'Action' column.
If the target sum was 26 instead of 22, what would happen at Step 5?
Asum==val would be true
Bsum==val would be false
CThe node would not be a leaf
DThe function would return false immediately
💡 Hint
Compare the remaining sum and node value at Step 5 in the execution table.
Concept Snapshot
Path Sum Root to Leaf in Binary Tree:
- Start at root, check if leaf node
- If leaf, compare remaining sum with node value
- If match, return true
- Else, recursively check left and right children with sum - node.Val
- Return true if any path matches, else false
Full Transcript
This concept checks if there is a path from the root to any leaf in a binary tree where the sum of node values equals a target sum. The process starts at the root node and checks if it is a leaf. If it is, it compares the remaining sum with the node's value. If they match, the path exists and returns true. If not a leaf, it recursively checks the left and right children, subtracting the current node's value from the sum. The execution table shows each step, the current node, remaining sum, and actions taken. Key moments clarify why leaf checks are important, what happens with an empty tree, and why the sum is updated. The visual quiz tests understanding of these steps. The snapshot summarizes the approach in simple steps.

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 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

    It is not about counting leaves, finding max depth, or summing all nodes, but specifically about 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 = target? [OK]
Hint: Focus on root-to-leaf paths, not entire tree sums [OK]
Common Mistakes:
  • Confusing path sum with total tree sum
  • Checking paths that don't end at leaf nodes
  • Ignoring the root node in the sum
2. Which of the following Go function signatures correctly represents a function to check path sum in a binary tree node defined as type TreeNode struct { Val int; Left, Right *TreeNode }?
easy
A. func hasPathSum(root TreeNode, sum int) bool
B. func hasPathSum(root *TreeNode, sum int) bool
C. func hasPathSum(root *TreeNode, sum int) int
D. func hasPathSum(root TreeNode, sum int) int

Solution

  1. Step 1: Identify correct parameter types

    The root node should be passed as a pointer to TreeNode to allow nil checks and avoid copying the entire node.
  2. Step 2: Identify correct return type

    The function should return a boolean indicating if such a path exists, not an integer.
  3. Final Answer:

    func hasPathSum(root *TreeNode, sum int) bool -> Option B
  4. Quick Check:

    Pointer param + bool return = correct signature [OK]
Hint: Use pointer receiver and bool return for path existence [OK]
Common Mistakes:
  • Passing TreeNode by value instead of pointer
  • Returning int instead of bool
  • Using incorrect parameter order
3. What is the output of the following Go code snippet?
package main

import "fmt"

type TreeNode struct {
  Val int
  Left, Right *TreeNode
}

func hasPathSum(root *TreeNode, sum int) bool {
  if root == nil {
    return false
  }
  if root.Left == nil && root.Right == nil {
    return root.Val == sum
  }
  return hasPathSum(root.Left, sum-root.Val) || hasPathSum(root.Right, sum-root.Val)
}

func main() {
  root := &TreeNode{5, &TreeNode{4, &TreeNode{11, &TreeNode{7, nil, nil}, &TreeNode{2, nil, nil}}, nil}, &TreeNode{8, &TreeNode{13, nil, nil}, &TreeNode{4, nil, &TreeNode{1, nil, nil}}}}
  fmt.Println(hasPathSum(root, 22))
}
medium
A. Compilation error
B. false
C. Runtime panic
D. true

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, so the function returns true.
  2. Step 2: Confirm function logic correctness

    The function correctly checks leaf nodes and recursively subtracts node values from sum, returning true if any path matches.
  3. Final Answer:

    true -> Option D
  4. Quick Check:

    Path 5+4+11+2 = 22 [OK]
Hint: Look for any root-to-leaf path summing to target [OK]
Common Mistakes:
  • Ignoring leaf node condition
  • Not subtracting node value from sum
  • Assuming sum must be at root only
4. The following Go function is intended to check if a path sum exists but has a bug. What is the bug?
func hasPathSum(root *TreeNode, sum int) bool {
  if root == nil {
    return false
  }
  if root.Left == nil && root.Right == nil {
    return sum == root.Val
  }
  return hasPathSum(root.Left, sum-root.Val) && hasPathSum(root.Right, sum-root.Val)
}
medium
A. Using && instead of || causes incorrect results
B. Missing base case for nil root
C. Incorrect comparison order in leaf check
D. Not subtracting root.Val from sum in recursive calls

Solution

  1. Step 1: Analyze recursive return condition

    The function uses logical AND (&&) to combine left and right subtree results, which requires both to be true.
  2. Step 2: Understand correct logic for path sum

    We want to return true if either left or right subtree has a valid path, so logical OR (||) should be used instead.
  3. Final Answer:

    Using && instead of || causes incorrect results -> Option A
  4. Quick Check:

    Use OR (||) to find any valid path [OK]
Hint: Use OR (||) to combine subtree results, not AND (&&) [OK]
Common Mistakes:
  • Using AND instead of OR in recursive calls
  • Forgetting to check leaf nodes properly
  • Not handling nil root correctly
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. Only consider paths with positive sums
B. Stop recursion early if sum becomes negative
C. No modification needed; the standard path sum check works for all values
D. Use breadth-first search instead of depth-first search

Solution

  1. Step 1: Understand path sum logic with negative values

    The standard recursive approach subtracts node values from sum and checks leaf nodes; negative values do not break this logic.
  2. Step 2: Evaluate unnecessary optimizations

    Stopping early on negative sums or ignoring negative paths can miss valid paths; BFS is not required for correctness.
  3. Final Answer:

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

    Standard DFS works with negatives [OK]
Hint: Standard DFS path sum works regardless of node values sign [OK]
Common Mistakes:
  • Stopping recursion on negative sums
  • Ignoring negative or zero values in paths
  • Switching to BFS 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