From c1e47ed96396c2730f4db1c4612b206e5009fb98 Mon Sep 17 00:00:00 2001 From: jojoo15 <75017412+jojoo15@users.noreply.github.com> Date: Mon, 17 May 2021 12:07:13 +0200 Subject: [PATCH] =?UTF-8?q?Update=200112.=E8=B7=AF=E5=BE=84=E6=80=BB?= =?UTF-8?q?=E5=92=8C.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 0112 and 0113 python version of code added --- problems/0112.路径总和.md | 69 +++++++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 3 deletions(-) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index ecbefd90..d25844dc 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -348,8 +348,71 @@ class Solution { ``` Python: - - +0112.路径总和 +```python +# 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: TreeNode, targetSum: int) -> bool: + def isornot(root,targetSum)->bool: + if (not root.left) and (not root.right) and targetSum == 0:return True // 遇到叶子节点,并且计数为0 + if (not root.left) and (not root.right):return False //遇到叶子节点,计数不为0 + if root.left: + targetSum -= root.left.val //左节点 + if isornot(root.left,targetSum):return True //递归,处理左节点 + targetSum += root.left.val //回溯 + if root.right: + targetSum -= root.right.val //右节点 + if isornot(root.right,targetSum):return True //递归,处理右节点 + targetSum += root.right.val //回溯 + return False + + if root == None:return False //别忘记处理空TreeNode + else:return isornot(root,targetSum-root.val) +``` +0113.路径总和-ii +```python +# 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 pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]: + path=[] + res=[] + def pathes(root,targetSum): + if (not root.left) and (not root.right) and targetSum == 0: // 遇到叶子节点,并且计数为0 + res.append(path[:]) //找到一种路径,记录到res中,注意必须是path[:]而不是path + return + if (not root.left) and (not root.right):return // 遇到叶子节点直接返回 + if root.left: //左 + targetSum -= root.left.val + path.append(root.left.val) //递归前记录节点 + pathes(root.left,targetSum) //递归 + targetSum += root.left.val //回溯 + path.pop() //回溯 + if root.right: //右 + targetSum -= root.right.val + path.append(root.right.val) //递归前记录节点 + pathes(root.right,targetSum) //递归 + targetSum += root.right.val //回溯 + path.pop() //回溯 + return + + if root == None:return [] //处理空TreeNode + else: + path.append(root.val) //首先处理根节点 + pathes(root,targetSum-root.val) + return res +``` Go: JavaScript: @@ -427,4 +490,4 @@ let pathSum = function (root, targetSum) { * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -