mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
@ -482,6 +482,52 @@ class Solution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
```java
|
||||||
|
// 解法3 DFS统一迭代法
|
||||||
|
class Solution {
|
||||||
|
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
|
||||||
|
List<List<Integer>> result = new ArrayList<>();
|
||||||
|
Stack<TreeNode> nodeStack = new Stack<>();
|
||||||
|
Stack<Integer> sumStack = new Stack<>();
|
||||||
|
Stack<ArrayList<Integer>> 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<Integer> 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
|
## python
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user