zoukankan      html  css  js  c++  java
  • LeetCode 112. 路径总和

    112. 路径总和

    Difficulty: 简单

    给你二叉树的根节点 root 和一个表示目标和的整数 targetSum ,判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum

    叶子节点 是指没有子节点的节点。

    示例 1:

    输入:root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
    输出:true
    

    示例 2:

    输入:root = [1,2,3], targetSum = 5
    输出:false
    

    示例 3:

    输入:root = [1,2], targetSum = 0
    输出:false
    

    提示:

    • 树中节点的数目在范围 [0, 5000]
    • -1000 <= Node.val <= 1000
    • -1000 <= targetSum <= 1000

    Solution

    运用二叉树的前序遍历,把从根节点到任意节点的路径和保存在一个tuple数据结构里面,如果前序遍历到了叶子节点,并且此时从根节点到该子节点的和等于target的时候,说明找到了满足目标和的路径。

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    ​
    class Solution:
        def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
            if not root:
                return False
            stack = [(root, root.val)]
            while stack:
                node, val = stack.pop()
                if not node.left and not node.right and val == targetSum:
                    return True
                if node.right:
                    stack.append((node.right, val + node.right.val))
                if node.left:
                    stack.append((node.left, val + node.left.val))
            return False
    

    相关题目:
    LeetCode 113. 路径总和 II - swordspoet - 博客园
    LeetCode 437. 路径总和 III - swordspoet - 博客园

  • 相关阅读:
    django 如何重用app
    vim常用命令
    linux find grep
    linux su su-的区别
    linux定时任务crontab
    linux shell的单行多行注释
    python字符串的截取,查找
    gdb调试
    python字符转化
    python读写文件
  • 原文地址:https://www.cnblogs.com/swordspoet/p/14805825.html
Copyright © 2011-2022 走看看