[LeetCode] 112. Path Sum, Easy

2025. 4. 7. 16:12·CodingTest/LeetCode
반응형

1. 문제

  • 이진 트리와 targetSum이 주어질 때, 리프노드까지의 경로 중 targetSum과 합이 같아지는 경로가 존재하는 지 판별하라.

2. 해결

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
    if(!root) return false;
    
    if(!root.left && !root.right) {
        return targetSum === root.val
    }
    
    const substractVal = targetSum - root.val;
    
    return hasPathSum(root.left, substractVal) || hasPathSum(root.right, substractVal);
};
  • 루트 노드부터 조건을 판별하며 targetSum이 0이되면 true를 반환하게 했는데, 이렇게 하면 이진 트리가 null이고 targetSum이 0인 경우도 true가 나와서 엣지 케이스 실패가 뜬다.
  • 리프 노드 판별 조건은 root가 null인것도 판별할 수 있지만, left와 right가 null인가로도 판별할 수 있다. 
저작자표시 (새창열림)
'CodingTest/LeetCode' 카테고리의 다른 글
  • [LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal, Medium
  • [LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal, Medium
  • [LeetCode] 101. Symmetric Tree, Easy
  • [LeetCode] 104. Maximum Depth of Binary Tree, Easy
뜸부깅
뜸부깅
코딩에 대한 여러 개인적인 생각을 정리하고 공부를 하는 공간입니다!!
  • 뜸부깅
    코오오딩
    뜸부깅
  • 전체
    오늘
    어제
    • Note (429)
      • Skill (31)
        • Java & Spring (9)
        • Javascript & HTML & CSS (0)
        • React (0)
        • Next.js (22)
      • CodingTest (389)
        • 백준 온라인 저지(BOJ) (140)
        • 프로그래머스(Programmers) (79)
        • LeetCode (170)
      • Algorithm & Data Structure (6)
      • [Project] 포트폴리오 (3)
        • Front end (3)
        • Back end (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    백준7576
    백준2751
    Easy
    boj2108
    leetcode 2236
    TypeScript
    자바
    백준7576자바
    백준1427
    백준
    meidum
    백준1260
    medium
    알고리즘
    component-scan
    boj1427
    Java
    BOJ
    next 14
    프로그래머스
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[LeetCode] 112. Path Sum, Easy
상단으로

티스토리툴바