From 87dbf5efc5e12ea3a305be097c2967ac3792e403 Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Sat, 18 Mar 2023 16:34:16 -0400 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 增加:0113 - python - 迭代法 - 前序遍历解法 --- problems/0112.路径总和.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index e412d38e..29e5a547 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -560,6 +560,26 @@ class Solution: return result ``` +**迭代法,前序遍历** + +```python +class Solution: + def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]: + if not root: return [] + stack, path_stack,result = [[root,root.val]],[[root.val]],[] + while stack: + cur,cursum = stack.pop() + path = path_stack.pop() + if cur.left==cur.right==None: + if cursum==targetSum: result.append(path) + if cur.right: + stack.append([cur.right,cursum+cur.right.val]) + path_stack.append(path+[cur.right.val]) + if cur.left: + stack.append([cur.left,cursum+cur.left.val]) + path_stack.append(path+[cur.left.val]) + return result +``` ## go ### 112. 路径总和