From 3f2a816f3096c6ccccba41c81b3975ca80f6d081 Mon Sep 17 00:00:00 2001 From: Lozakaka <102352821+Lozakaka@users.noreply.github.com> Date: Tue, 18 Apr 2023 18:23:24 -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 新增java 統一迭代法 --- ...57\345\276\204\346\200\273\345\222\214.md" | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git "a/problems/0112.\350\267\257\345\276\204\346\200\273\345\222\214.md" "b/problems/0112.\350\267\257\345\276\204\346\200\273\345\222\214.md" index 5958de93e6..b145788794 100644 --- "a/problems/0112.\350\267\257\345\276\204\346\200\273\345\222\214.md" +++ "b/problems/0112.\350\267\257\345\276\204\346\200\273\345\222\214.md" @@ -385,6 +385,42 @@ class solution { } } ``` +```Java 統一迭代法 + public boolean hasPathSum(TreeNode root, int targetSum) { + Stack treeNodeStack = new Stack<>(); + Stack sumStack = new Stack<>(); + + if(root == null) + return false; + treeNodeStack.add(root); + sumStack.add(root.val); + + while(!treeNodeStack.isEmpty()){ + TreeNode curr = treeNodeStack.peek(); + int tempsum = sumStack.pop(); + if(curr != null){ + treeNodeStack.pop(); + treeNodeStack.add(curr); + treeNodeStack.add(null); + sumStack.add(tempsum); + if(curr.right != null){ + treeNodeStack.add(curr.right); + sumStack.add(tempsum + curr.right.val); + } + if(curr.left != null){ + treeNodeStack.add(curr.left); + sumStack.add(tempsum + curr.left.val); + } + }else{ + treeNodeStack.pop(); + TreeNode temp = treeNodeStack.pop(); + if(temp.left == null && temp.right == null && tempsum == targetSum) + return true; + } + } + return false; + } +``` ### 0113.路径总和-ii