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.
#DFS #이진트리 #연결리스트
깊이우선탐색으로 모든 루트를 방문한 뒤, 최종 합계가 targetSum과 같으면 True를 리턴한다.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
def dfs(node, s):
s += node.val
if node.left is None and node.right is None:
if s == targetSum:
return True
l, r = False, False
if node.left is not None:
l = dfs(node.left, s)
if node.right is not None:
r = dfs(node.right, s)
#좌측 노드와 우측 노드 중 하나라도 targetSum을 만족하면 True를 리턴한다.
return l or r
if root is None:
return False
return dfs(root, 0)
Runtime: 89 ms, faster than 26.85% of Python3 online submissions for Path Sum.
Memory Usage: 15 MB, less than 91.98% of Python3 online submissions for Path Sum.