112. 路经总和

问题描述

https://leetcode.cn/problems/path-sum/description/

解题思路

我们可以对叶子结点进行判断,如果叶子结点的值等于targetSum,那么就算是找到了。

代码

# 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:
        if root is None:
            return False
        if root.left is None and root.right is None:
            return targetSum == root.val
        return self.hasPathSum(root.left, targetSum-root.val) or self.hasPathSum(root.right, targetSum-root.val)

 

posted @ 2023-01-28 17:35  BJFU-VTH  阅读(15)  评论(0编辑  收藏  举报