首页 > 其他分享 >112. 路经总和

112. 路经总和

时间:2023-01-28 17:45:26浏览次数:37  
标签:路经 None right val self targetSum 112 root 总和

问题描述

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)

 

标签:路经,None,right,val,self,targetSum,112,root,总和
From: https://www.cnblogs.com/bjfu-vth/p/17070968.html

相关文章