https://leetcode.com/problems/path-sum/
root ~ leaf까지의 path 합 중 목표 합과 동일한 것이 있는지에 대한 여부 반환
DFS로 path이면서 targetSum이랑 같을 때 true, 아닌 경우 false 반환
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public int target;
public bool HasPathSum(TreeNode root, int targetSum) {
if (root == null) return false;
target = targetSum;
return CheckPathSum(root, 0);
}
public bool CheckPathSum(TreeNode currNode, int currSum)
{
if (currNode == null) return false; // left, right null 나올 수 있으므로 처리
if (currNode.left == null && currNode.right == null && currSum + currNode.val == target) return true;
return CheckPathSum(currNode.left, currSum + currNode.val) || CheckPathSum(currNode.right, currSum + currNode.val);
}
}