Leetcode 112. 路径总和 (每日一题 20210910)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 112. 路径总和 (每日一题 20210910)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給你二叉樹的根節(jié)點(diǎn)?root 和一個(gè)表示目標(biāo)和的整數(shù)?targetSum ,判斷該樹中是否存在 根節(jié)點(diǎn)到葉子節(jié)點(diǎn) 的路徑,這條路徑上所有節(jié)點(diǎn)值相加等于目標(biāo)和?targetSum 。葉子節(jié)點(diǎn) 是指沒有子節(jié)點(diǎn)的節(jié)點(diǎn)。示例 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鏈接:https://leetcode-cn.com/problems/path-sumclass Solution:def haspathSum(self, root:Option[TreeNode], targetSum:int)->bool:#解法一if not root:return Falseif not root.left and not root.right:return root.val == targetSumreturn self.haspathSum(root.right, targetSum-root.val) or self.haspathSum(root.left, targetSum-root.val)#解法二stack = [(root, root.val)]while stack:node, value = stack.pop()if not node.left and not node.right and val == targetSum:return Trueif node.left:stack.append((root.left, value + root.left.val))if node.right:stack.append((root.right, value + root.right.val))return False
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀
總結(jié)
以上是生活随笔為你收集整理的Leetcode 112. 路径总和 (每日一题 20210910)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode 189. 旋转数组 (
- 下一篇: Leetcode 217. 存在重复元素