Check for Root-to-Leaf Path with Target Sum
Problem Statement:
2 min readJul 12, 2024
Given a binary tree and an integer target
, check whether there is a root-to-leaf path with its sum equal to the target.
Examples:
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: The root-to-leaf path with the target sum is shown.
Example 2:
Input: root = [1,2,3], targetSum = 5
Output: false
Explanation: There two root-to-leaf paths in the tree:
(1 --> 2): The sum is 3.
(1 --> 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
Constraints:
1 ≤ number of nodes ≤ 10^4
1 ≤ target ≤ 10^6
Solution Approach:
Observation: To determine if there is a root-to-leaf path with a given sum, we need to explore all paths from the root to the leaf nodes and check their sums against the target. We can achieve this using a recursive depth-first search (DFS) approach.
Recursive Approach:
- Base Case:
- If the current node is
null
, returnfalse
. - If the current node is a leaf node (both left and right children are
null
), check if thetarget
equals the node's value.
2. Recursive Case:
- Recursively check the left and right subtrees with the updated target (
target - root.data
).
Steps:
- Start from the root node.
- Subtract the node’s value from the target sum.
- Recursively check the left and right subtrees.
- If either subtree returns
true
, returntrue
. - If both subtrees return
false
, returnfalse
.
This approach ensures we explore all paths from the root to the leaves, checking their sums against the target.
Code Implementation:
/*
class Node{
int data;
Node left;
Node right;
Node(int data){
this.data = data;
left=null;
right=null;
}
}
*/
class Solution {
boolean hasPathSum(Node root, int target) {
if (root == null) return false;
// If it's a leaf node, check if the current sum equals target
if (root.left == null && root.right == null) {
return target == root.data;
}
// Recur for left and right subtrees with the reduced target sum
return hasPathSum(root.left, target - root.data) || hasPathSum(root.right, target - root.data);
}
}
Complexity Analysis:
- Time Complexity:
O(n)
wheren
is the number of nodes in the tree. This is because we visit each node exactly once. - Space Complexity:
O(h)
whereh
is the height of the tree. This is due to the recursive stack space, which in the worst case (skewed tree) could beO(n)
.