엔지니어 게시판
LeetCode 솔루션 분류

[9/24] 113. Path Sum II

컨텐츠 정보

본문

113. Path Sum II
Medium
6053126Add to ListShare

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references.

root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

 

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: [[5,4,11,2],[5,8,4,5]]
Explanation: There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22

Example 2:

Input: root = [1,2,3], targetSum = 5
Output: []

Example 3:

Input: root = [1,2], targetSum = 0
Output: []

 

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000
Accepted
668,448
Submissions
1,192,492

관련자료

댓글 1

학부유학생님의 댓글

  • 익명
  • 작성일
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
        res = []
        
        def dfs(part, curr):
            if not curr: return
            
            part.append(curr.val)
            path_sum = sum(part)
            
            if (not curr.left) and (not curr.right) and (path_sum == targetSum):
                res.append(part.copy())
            else:            
                dfs(part, curr.left)
                dfs(part, curr.right)
            part.pop()
        
        dfs([],root)
        
        return res
            
전체 404 / 8 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 773 명
  • 오늘 방문자 7,135 명
  • 어제 방문자 6,975 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,537 명
알림 0