leetcode-路径总和

112. 路径总和

# 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 traversal(root, count):
            # 遇到叶子节点且count为0
            if not root.left and not root.right and count == 0:
                return True
            # 遇到叶子节点直接返回False
            if not root.left and not root.right:
                return False
            # 左右子节点不为空,进行回溯
            if root.left:
                count -=  root.left.val
                if traversal(root.left, count):
                    return True
                count += root.left.val
            if root.right:
                count -= root.right.val
                if traversal(root.right, count):
                    return True
                count += root.right.val
            return False
        if not root:
            return False
        return traversal(root, targetSum - root.val)

你可能感兴趣的:(leetcode)