DEV Community

Tanuja V
Tanuja V

Posted on • Edited on

3 1 1 1

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);

    }
}
Enter fullscreen mode Exit fullscreen mode

Verdict : 100 / 117 test cases passed.

Hidden test case gives the clear picture of the entirety of the question.

Hidden test case

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);

    }
}

Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more