# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def hasPathSum(self, root, targetSum):
"""
:type root: TreeNode
:type targetSum: int
:rtype: bool
"""
# 节点可能为None
if not root:
return False
stack = []
stack.append((root, root.val))
while stack:
cur, path_sum = stack.pop()
if not cur.left and not cur.right and path_sum == targetSum:
return True
# 中左右顺序,代码中右左
if cur.right:
stack.append((cur.right, path_sum + cur.right.val))
if cur.left:
stack.append((cur.left, path_sum + cur.left.val))
return False
路径总和python(leetcode112)
最新推荐文章于 2022-08-06 22:24:15 发布