From ad2acdb14ac6d633a0ad6e3b8f92d3e1f6c32881 Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Thu, 20 Apr 2023 23:44:00 -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 add java iteration method for leetcode 113 (DFS统一迭代法) --- problems/0112.路径总和.md | 46 +++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/problems/0112.路径总和.md b/problems/0112.路径总和.md index 5958de93..d8ea0a18 100644 --- a/problems/0112.路径总和.md +++ b/problems/0112.路径总和.md @@ -446,6 +446,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