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. 路径总和