Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit ad2acdb

Browse files
Update 0112.路径总和.md
add java iteration method for leetcode 113 (DFS统一迭代法)
1 parent f848b4f commit ad2acdb

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎problems/0112.路径总和.md‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,52 @@ class Solution {
446446
}
447447
}
448448
```
449+
```java
450+
// 解法3 DFS统一迭代法
451+
class Solution {
452+
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
453+
List<List<Integer>> result = new ArrayList<>();
454+
Stack<TreeNode> nodeStack = new Stack<>();
455+
Stack<Integer> sumStack = new Stack<>();
456+
Stack<ArrayList<Integer>> pathStack = new Stack<>();
457+
if(root == null)
458+
return result;
459+
nodeStack.add(root);
460+
sumStack.add(root.val);
461+
pathStack.add(new ArrayList<>());
462+
463+
while(!nodeStack.isEmpty()){
464+
TreeNode currNode = nodeStack.peek();
465+
int currSum = sumStack.pop();
466+
ArrayList<Integer> currPath = pathStack.pop();
467+
if(currNode != null){
468+
nodeStack.pop();
469+
nodeStack.add(currNode);
470+
nodeStack.add(null);
471+
sumStack.add(currSum);
472+
currPath.add(currNode.val);
473+
pathStack.add(new ArrayList(currPath));
474+
if(currNode.right != null){
475+
nodeStack.add(currNode.right);
476+
sumStack.add(currSum + currNode.right.val);
477+
pathStack.add(new ArrayList(currPath));
478+
}
479+
if(currNode.left != null){
480+
nodeStack.add(currNode.left);
481+
sumStack.add(currSum + currNode.left.val);
482+
pathStack.add(new ArrayList(currPath));
483+
}
484+
}else{
485+
nodeStack.pop();
486+
TreeNode temp = nodeStack.pop();
487+
if(temp.left == null && temp.right == null && currSum == targetSum)
488+
result.add(new ArrayList(currPath));
489+
}
490+
}
491+
return result;
492+
}
493+
}
494+
```
449495

450496
## python
451497

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /