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 bc07169abb..51aa195676 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