Given the root
of a binary tree and an integer targetSum
, return true
if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum
.
A leaf is a node with no children.
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 are 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.
Example 3:
Input: root = [], targetSum = 0 Output: false Explanation: Since the tree is empty, there are no root-to-leaf paths.
Constraints:
[0, 5000]
.-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
Given the root of a binary tree and an integer targetSum
, determine if there exists a root-to-leaf path such that adding up all the values along the path equals targetSum
. A leaf is a node with no children.
The most efficient approach to solving this problem is using Depth-First Search (DFS). DFS recursively explores the tree, checking each path from the root to a leaf.
Algorithm:
Base Case: If the current node is null
, there's no path, so return false
.
Leaf Node Check: If the current node is a leaf node (both left
and right
children are null
), check if the current path sum (currentSum
) equals the targetSum
. If they are equal, return true
; otherwise, return false
.
Recursive Calls: Recursively call the DFS function on the left and right subtrees, updating the currentSum
by adding the current node's value. If either recursive call returns true
, it means a path with the target sum was found, so return true
. Otherwise, return false
.
Time Complexity: O(N), where N is the number of nodes in the tree. We visit each node at most once.
Space Complexity: O(H), where H is the height of the tree. This is due to the recursive call stack. In the worst case (a skewed tree), H can be equal to N.
The following code implements the DFS solution in several programming languages:
Python:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
def dfs(node, currentSum):
if not node:
return False
currentSum += node.val
if not node.left and not node.right: # Leaf node
return currentSum == targetSum
return dfs(node.left, currentSum) or dfs(node.right, currentSum)
return dfs(root, 0)
Java:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
return dfs(root, targetSum, 0);
}
private boolean dfs(TreeNode node, int targetSum, int currentSum) {
if (node == null) {
return false;
}
currentSum += node.val;
if (node.left == null && node.right == null) { // Leaf node
return currentSum == targetSum;
}
return dfs(node.left, targetSum, currentSum) || dfs(node.right, targetSum, currentSum);
}
}
C++:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
return dfs(root, targetSum, 0);
}
bool dfs(TreeNode* node, int targetSum, int currentSum) {
if (!node) return false;
currentSum += node->val;
if (!node->left && !node->right) return currentSum == targetSum;
return dfs(node->left, targetSum, currentSum) || dfs(node->right, targetSum, currentSum);
}
};
Go:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func hasPathSum(root *TreeNode, targetSum int) bool {
return dfs(root, targetSum, 0)
}
func dfs(node *TreeNode, targetSum, currentSum int) bool {
if node == nil {
return false
}
currentSum += node.Val
if node.Left == nil && node.Right == nil { //Leaf node
return currentSum == targetSum
}
return dfs(node.Left, targetSum, currentSum) || dfs(node.Right, targetSum, currentSum)
}
//Similar implementations can be provided for other languages like JavaScript, TypeScript, and Rust, following the same logical structure. The core idea remains consistent across all languages.