import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @param sum int整型
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
// write code here
ArrayList<ArrayList<Integer>> pathSums = new ArrayList<>();
if (root == null) return pathSums;
Deque<TreeNode> nodes = new ArrayDeque<>();
nodes.push(root);
Map<TreeNode,TreeNode> parents = new HashMap<>();
Map<TreeNode,Integer> sums = new HashMap<>();
parents.put(root,null);
sums.put(root,root.val);
while(!nodes.isEmpty()) {
TreeNode parent = nodes.poll();
if (parent.left != null) {
int val = parent.left.val;
nodes.add(parent.left);
parents.put(parent.left,parent);
sums.put(parent.left,val + sums.get(parent));
} else if (parent.right == null && sums.get(parent) == sum) {
TreeNode tmpParent = parent;
ArrayList<Integer> pathSum = new ArrayList<>();
while(tmpParent != null) {
pathSum.add(0,tmpParent.val);
tmpParent = parents.get(tmpParent);
}
pathSums.add(pathSum);
}
if (parent.right != null) {
int val = parent.right.val;
nodes.add(parent.right);
parents.put(parent.right,parent);
sums.put(parent.right,val + sums.get(parent));
}
}
System.out.println("=========" + pathSums.size());
return pathSums;
}
}
07-31
1268
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-07
1858
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-29
2426
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-28