본문 바로가기
LeetCode

LeetCode 112 Path Sum

by 콩순이냉장고 2021. 11. 14.

문제 URL : https://leetcode.com/problems/path-sum/submissions/

 

Path Sum - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제 접근법 : 루트에서 리프노드까지 경로의 합을 다구하여 targetSum을 구하는 문제입니다.

루트에서 리프노드까지의 합을 구하여 tarsum이 하나라도 있으면 됩니다.

 

소스코드 : 

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
//By 콩순이냉장고
/**
 * 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==NULL)return false;
        return dfs(root,targetSum);
    }
    bool dfs(TreeNode* root, int targetSum,int sum=0){
        if(!root->left&&!root->right){
            return sum+root->val==targetSum;
        }
        bool flag=false;
        if(root->left)
            flag|=dfs(root->left,targetSum,sum+root->val);
        if(root->right)
            flag|=dfs(root->right,targetSum,sum+root->val);
        return flag;
    }
};
cs

궁금한점 혹은 모르는점 어떤 질문이든 댓글은 언제나 환영입니다.

 

'LeetCode' 카테고리의 다른 글

LeetCode  (0) 2022.11.11
LeetCode 74 Search a 2D Matrix  (0) 2021.11.17
LeetCode 257 Binary Tree Paths  (0) 2021.11.14
LeetCode 103. Binary Tree Zigzag Level Order Traversal  (0) 2021.08.03
LeetCode 686. Repeated String Match  (0) 2021.07.31