diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 0a4f5714..39285a3b 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -482,6 +482,52 @@ class Solution { } } ``` +```java +// 解法3 DFS统一迭代法 +class Solution { + public List> pathSum(TreeNode root, int targetSum) { + List> result = new ArrayList<>(); + Stack nodeStack = new Stack<>(); + Stack sumStack = new Stack<>(); + Stack> pathStack = new Stack<>(); + if(root == null) + return result; + nodeStack.add(root); + sumStack.add(root.val); + pathStack.add(new ArrayList<>()); + + while(!nodeStack.isEmpty()){ + TreeNode currNode = nodeStack.peek(); + int currSum = sumStack.pop(); + ArrayList currPath = pathStack.pop(); + if(currNode != null){ + nodeStack.pop(); + nodeStack.add(currNode); + nodeStack.add(null); + sumStack.add(currSum); + currPath.add(currNode.val); + pathStack.add(new ArrayList(currPath)); + if(currNode.right != null){ + nodeStack.add(currNode.right); + sumStack.add(currSum + currNode.right.val); + pathStack.add(new ArrayList(currPath)); + } + if(currNode.left != null){ + nodeStack.add(currNode.left); + sumStack.add(currSum + currNode.left.val); + pathStack.add(new ArrayList(currPath)); + } + }else{ + nodeStack.pop(); + TreeNode temp = nodeStack.pop(); + if(temp.left == null && temp.right == null && currSum == targetSum) + result.add(new ArrayList(currPath)); + } + } + return result; + } +} +``` ## python