Problem
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.
Examples
Example 1:
graph TD; A[5] --> B[4] & C[8] B --> D[11] & E[null] C --> F[13] & G[4] D --> H[7] & I[2] G --> L[5] & M[1] style A fill:#f9f style B fill:#f9f style D fill:#f9f style I fill:#f9f
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Explanation: Following root-to-leaf path exists: [5,4,11,2], marked with () tree. There can be multiple paths, but we have to just return boolean value for that.
Example 2:
1
/ \
2 3
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.
Example 3:
Input: root = [], targetSum = 0
Output: false
Explanation: Since the tree is empty, there are no root-to-leaf paths.
Solution
Method 1 - Using Recursion
Code
Java
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null){
return false;
}
if(root.left == null && root.right == null){
return root.val == targetSum;
}
targetSum = targetSum - root.val;
return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum)
}
Method 2 - Using Queue
Code
Java
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
Queue<TreeNode> nodes = new LinkedList<TreeNode>();
Queue<Integer> values = new LinkedList<Integer>();
nodes.add(root);
values.add(root.val);
while(!nodes.isEmpty()){
TreeNode curr = nodes.poll();
int sumValue = values.poll();
if(curr.left == null && curr.right == null && sumValue==sum){
return true;
}
if(curr.left != null){
nodes.add(curr.left);
values.add(sumValue + curr.left.val);
}
if(curr.right != null){
nodes.add(curr.right);
values.add(sumValue + curr.right.val);
}
}
return false;
}