Our Feeds

Saturday, 19 October 2024

AJITH KP

112. Path Sum - LeetCode Solution

 112. Path Sum - LeetCode Solution in 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 printPath(TreeNode* node, int sum, int targetSum) { 
        if(node == nullptr) return false;
        if(node->left == nullptr && node->right == nullptr) {
            if(sum + node->val == targetSum) {
                return true;
            }
        }
        bool l = printPath(node->left, sum + node->val, targetSum);
        bool r = printPath(node->right, sum + node->val, targetSum);
        return l||r;
    }
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(root == nullptr) return false;
        return printPath(root, 0, targetSum);
    }
};

Latest