This content originally appeared on DEV Community and was authored by Flame Chan
LeetCode No. 112. Path Sum
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.
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null){
return false;
}
return sumOfPath(root, 0, targetSum);
}
public boolean sumOfPath(TreeNode cur, int sum, int target){
if(cur == null){
return false;
}
sum += cur.val;
if(cur.left == null && cur.right == null){
return sum==target;
}
return sumOfPath(cur.left, sum, target) || sumOfPath(cur.right,sum, target);
}
This content originally appeared on DEV Community and was authored by Flame Chan

Flame Chan | Sciencx (2024-06-21T13:40:46+00:00) LeetCode Day 13 Binary Tree Part 4. Retrieved from https://www.scien.cx/2024/06/21/leetcode-day-13-binary-tree-part-4/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.