0
点赞
收藏
分享

微信扫一扫

路径总和python(leetcode112)

112. 路径总和

# 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

举报

相关推荐

0 条评论