[LeetCode] 112.Path Sum

LeetCode#112

kimji1
Apr 9, 2021

문제

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

풀이 과정

1. 
-1000 < targetSum < 1000 이므로, targetSum의 값을 직접적으로 건드리면 기준값을 알기 어렵다.
2.
divide & conqure 로 풀이한다.
마지막 노드인 경우 targetSum과 현재 노드까지의 sum을 비교하여
일치하는 경우 true
일치하지 않는 경우 false
마지막 노드가 아닌 경우 다음 자식 노드에 대해서 같은 일을 반복한다.
3.7번 라인의 조건문처럼 root 노드가 마지막 노드이자 targetSum과 동일한 값을 가지는 경우 true를 반환하도록 예외 처리를 해준다.

--

--

kimji1
kimji1

No responses yet