728x90
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
if root is None:
return False
if root.left is None and root.right is None and root.val == sum:
return True
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
sum - curr_value 하면서 left, right node를 계속 탐색하다가 leaf 에 도착했을때 curr_value == sum-curr_value 이면 True
출처: github.com/jiapengwen/LeetCode/blob/master/Python/path-sum.py
728x90
'Leetcode' 카테고리의 다른 글
[LeetCode] Best Time to Buy and Sell Stocks python (0) | 2021.04.01 |
---|---|
[LeetCode] Pascal's Triangle 파이썬 (+Pascal's Triangle II) (0) | 2021.04.01 |
[LeetCode] Minimum Depth of Binary Tree 파이썬 (recursion) (0) | 2021.04.01 |
[LeetCode] Balance Binary Tree python 파이썬 (recursion) (0) | 2021.04.01 |
[LeetCode] Convert Sorted Array to Binary Tree python 파이썬 (recursion, median) (0) | 2021.04.01 |
댓글