From 564fbff98393bc4a720baf61d343864600a50f90 Mon Sep 17 00:00:00 2001 From: SuperVishal0 <115384297+SuperVishal0@users.noreply.github.com> Date: Mon, 31 Oct 2022 11:16:39 +0530 Subject: [PATCH] Create Path sum --- Path sum | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Path sum diff --git a/Path sum b/Path sum new file mode 100644 index 0000000..2a7b283 --- /dev/null +++ b/Path sum @@ -0,0 +1,41 @@ +/** +//////////////////////////////////////// +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. + + + +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. + + +////////////////////////////////////////// + + * 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 hasPathSum(TreeNode* root, int targetSum) { + if(!root) return false; // base case + if(!root->left and !root->right){ // when you are at leaf node + if(root->val==targetSum) return true; // check if matches or not + else return false; + } + // recursive case + return hasPathSum(root->left,targetSum-root->val) || hasPathSum(root->right,targetSum-root->val); + } +};