Leetcode 112: Path Sum

Subject:
Insert picture description here
python3 code:

# 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: TreeNode, sum: int) -> bool:
        if not root:
            return False
        if not root.left and not root.right and sum == root.val:
            return True
        lefttree = self.hasPathSum(root.left, sum-root.val)
        righttree = self.hasPathSum(root.right, sum-root.val)
        if lefttree or righttree:
            return True
        else:
            return False

Idea:
Use the recursive idea. Since the function returns the bool type, so long as the value of sum is continuously decreased, if the value is decreased to 0, it will return True, which means that Path is in the BST. Otherwise, there is no Path in BST.

If you feel good, please like or follow or leave a message~
Thank you~

Guess you like

Origin blog.csdn.net/BSCHN123/article/details/112655212