[E] 112. Path Sum

YJ·2025년 5월 5일

leetcode

목록 보기
80/100

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

문제

이진 트리 주어졌을 때 root 부터 leaf 까지 합의 최대

답안

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

    public boolean hasPathSum(TreeNode root, int targetSum) {
        dfs(root, 0);
        return sums.contains(targetSum);
    }

    public void dfs(TreeNode root, int sum) {
        if (root != null) {
            sum += root.val;
            if (root.left == null && root.right == null) {
                sums.add(sum);
            }
            dfs(root.left, sum);
            dfs(root.right, sum);
        }
    }
}

메모

클래스 변수 없이 차감하면서 하는 방식도 있다. 더 깔끔하고 보기 좋긴 한듯.

public boolean hasPathSum(TreeNode root, int targetSum) {
	return dfs(root, targetSum);
}

private boolean dfs(TreeNode node, int remaining) {
	if (node == null) {
		return false;
	}
	remaining -= node.val;

	if (node.left == null && node.right == null) {
		return remaining == 0;
	}
	return dfs(node.left, remaining) || dfs(node.right, remaining);
}
profile
Hello

0개의 댓글