tree 구조에서 첫 노드부터 마지막 노드 값의 합이 target sum과 같은지 판별하는 문제이다.
/**
* 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;
targetSum -= root->val;
if(targetSum == 0 && !root->left && !root->right) return true;
return hasPathSum(root->left, targetSum) || hasPathSum(root->right, targetSum);
}
};