Path Sum
To solve this coding challenge, we need to determine if there exists a root-to-leaf path in a binary tree such that the sum of the values along the path equals a given target sum. Each node on the path contributes to the total sum, and a leaf is defined as a node with no children.
Explanation
The task is to traverse the binary tree starting from the root and to check if there is any path from the root to a leaf that sums up to the target sum. This can effectively be done using a recursive depth-first search (DFS) approach. Here are the detailed steps to achieve this:- Base case checks:
-
If the root is
null
false
- Leaf node check:
-
If the current node is a leaf (i.e., it has no left or right children), check if its value equals the current target sum. If true, return
true
false
- Recursive step:
- If the current node is not a leaf, recursively call the function for its left and right children with the updated target sum (original target sum minus the current node's value).
-
If any of the recursive calls return
true
true
false
- Initial Function Call:
-
Begin with the first call to
hasPathSum(root, targetSum)
-
The
root
targetSum
- Checking for null root:
-
If the
root
null
false
- Leaf Node Check:
-
If the current node (initially the
root
null
-
Compare the value of the node with the
targetSum
-
If they are equal, return
true
-
If they are not equal, return
false
- Recursive Calls:
- For non-leaf nodes:
-
Make a recursive call to the left child with the updated target sum (
targetSum - node.value
-
Similarly, make another recursive call to the right child with the updated target sum (
targetSum - node.value
-
Store the results of these calls in variables
leftHasPath
rightHasPath
- Result Compilation:
-
If either
leftHasPath
rightHasPath
true
true
-
If both are
false
false
Pseudocode
Here is the pseudocode with comprehensive comments for our solution:
Function hasPathSum(node, targetSum):
# Base case: if the node is null, we return false because no path can exist within a null tree.
If node is null:
Return false
# Check if the node is a leaf
If node.left is null AND node.right is null:
# If it is a leaf, check if the node's value is equal to the remaining targetSum
If node.value equals targetSum:
Return true
Else:
Return false
# Recursive call on the left child with updated targetSum
leftHasPath = hasPathSum(node.left, targetSum - node.value)
# Recursive call on the right child with updated targetSum
rightHasPath = hasPathSum(node.right, targetSum - node.value)
# If any of the recursive calls return true, we have found a valid path
Return leftHasPath OR rightHasPath