[M] 113. Path Sum II

YJ·2025년 5월 5일

leetcode

목록 보기
81/100

https://leetcode.com/problems/path-sum-ii

문제

이진 트리에서 root 부터 leaf 까지의 합이 주어진 숫자가 되는 경로를 모두 반환하기

답안

class Solution {
    private List<List<Integer>> paths = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        dfs(root, new ArrayList<>(), targetSum);
        return paths;
    }

    public void dfs(TreeNode root, List<Integer> path, int targetSum) {
        if (root == null) {
            return;
        }
        path.add(root.val);
        if (root.left == null && root.right == null && targetSum == root.val) {
            paths.add(new ArrayList<Integer>(path)); // 복사본 저장
        } 
        dfs(root.left, path, targetSum - root.val);
        dfs(root.right, path, targetSum - root.val);
        path.remove(path.size() - 1);
    }
}

메모

112 와 비슷하지만.. 현재까지 방문한 경로를 저장해야 하므로 Backtracking 이 필요하다.
path.remove(path.size() - 1) 가 백트래킹 부분.. 다른 경로 탐색 시 이전 경로값들이 남지 않는다.
Backtracking 원칙: 자기가 추가한 원소는 자기가 제거한다.

profile
Hello

0개의 댓글