[LeetCode] Path Sum

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 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 {
bool res = false;
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(!root) return false;
return healper(root, targetSum);
}

bool healper(TreeNode* root, int targetSum) {
if(!root) return false;
if(!root->left and !root->right) {
if(targetSum == root->val) res = true;
return res;
}
healper(root->left, targetSum - root->val);
healper(root->right, targetSum - root->val);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/20/PS/LeetCode/path-sum/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.