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)

相关推荐

  1. leetcode 437 路径总和

    2024-01-20 22:36:02       58 阅读
  2. leetcode-路径总和

    2024-01-20 22:36:02       68 阅读
  3. leetcode112.路径总和

    2024-01-20 22:36:02       39 阅读
  4. LeetCode112 路径总和

    2024-01-20 22:36:02       41 阅读
  5. LeetCode437题:路径总和III(python3)

    2024-01-20 22:36:02       47 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-20 22:36:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-20 22:36:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-20 22:36:02       82 阅读
  4. Python语言-面向对象

    2024-01-20 22:36:02       91 阅读

热门阅读

  1. C语言零基础入门(结构体)

    2024-01-20 22:36:02       53 阅读
  2. 解决Spring Boot应用打包后文件访问问题

    2024-01-20 22:36:02       69 阅读
  3. 多模态是什么意思,在生活工业中有哪些应用?

    2024-01-20 22:36:02       106 阅读
  4. Python Matplotlib 实现基础绘图

    2024-01-20 22:36:02       60 阅读
  5. 题记(18)--日志排序

    2024-01-20 22:36:02       63 阅读
  6. SpringBoot+Redisson分布式锁

    2024-01-20 22:36:02       61 阅读
  7. 如何在ubuntu18.04安装python3.8.6

    2024-01-20 22:36:02       59 阅读
  8. Android System Service系统服务--1

    2024-01-20 22:36:02       60 阅读