LeetCode 풀기 - 112. Path Sum

백지우·2026년 9월 6일

LeetCode

목록 보기
30/76
  • LeetCode 최소 하루에 하나는 풀자는 마인드
  • 사용언어: JAVA

112. Path Sum

풀이

  • 방법:leaf인지 확인 -> left , right DFS 탐색
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        
        if (root == null) return false;

        int newVal = targetSum - root.val;

        if (root.left == null && root.right == null) {
            return newVal == 0;
        }

        return hasPathSum(root.left, newVal) || hasPathSum(root.right, newVal);
        
    }
}

0개의 댓글