An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
April 19, 2024 04:01 am GMT
Original Link: https://dev.to/tanujav/path-sum-leetcode-java-3837
Path Sum | LeetCode | Java
According to the problem we have to find the sum from every root-to-leaf path and check whether it is equal to the targetSum.
So, the intuitive code will be
class Solution { public boolean hasPathSum(TreeNode root, int targetSum) { return pathSum(root, 0, targetSum); } boolean pathSum(TreeNode node, int sum, int targetSum){ if(node==null) return false; sum += node.val; if(sum==targetSum) return true; return pathSum(node.left, sum, targetSum) || pathSum(node.right, sum, targetSum); }}
Verdict : 100 / 117 test cases passed.
Hidden test case gives the clear picture of the entirety of the question.
Our sum should not be just based on node value but root-to-leaf path.
After reaching the leaf node only are we allowed to take the sum of it.
So, the code modifies slightly.
class Solution { public boolean hasPathSum(TreeNode root, int targetSum) { return pathSum(root, 0, targetSum); } boolean pathSum(TreeNode node, int sum, int targetSum){ if(node==null) return false; sum += node.val; //we are adding the condition to identify leaf node. If node.left and node.right==null indicates the "Leaf Node" if(node.left==null && node.right==null && sum==targetSum) return true; return pathSum(node.left, sum, targetSum) || pathSum(node.right, sum, targetSum); }}
Thanks for reading.
Feel free to comment and like the post
Follow for more && Happy Coding
Don't forget to check-out my other socials:
Github
Hashnode
Medium
Twitter(X)
Original Link: https://dev.to/tanujav/path-sum-leetcode-java-3837
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To