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 원칙: 자기가 추가한 원소는 자기가 제거한다.