(1) DFS
List<List<Integer>> res = new LinkedList<List<Integer>>();
Deque<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
dfs(root, target);
return res;
}
public void dfs(TreeNode root, int target){
if(root == null) return;
path.addLast(root.val);
target -= root.val;
if(root.left == null && root.right == null && target ==0){
res.add(new LinkedList<Integer>(path) );
}
dfs(root.left, target);
dfs(root.right, target);
path.pollLast();
}
(2)BFS +哈希表记录每个节点的父节点。
List<List<Integer>> res = new LinkedList<List<Integer>>();
Map<TreeNode, TreeNode> map = new HashMap<TreeNode,TreeNode>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
if(root == null ) return res;
Queue<TreeNode> nodeQueue = new LinkedList<>();
Queue<Integer> sumQueue = new LinkedList<>();
nodeQueue.offer(root);
sumQueue.offer(0);
while(!nodeQueue.isEmpty()){
TreeNode node = nodeQueue.poll();
int tmp = sumQueue.poll() + node.val;
if(node.left == null && node.right == null && tmp == target){
getPath(node);
}
if( node.left != null){
map.put(node.left, node);
nodeQueue.offer(node.left);
sumQueue.offer(tmp);
}
if( node.right != null){
map.put(node.right, node);
nodeQueue.offer(node.right);
sumQueue.offer(tmp);
}
}
return res;
}
private void getPath(TreeNode node) {
LinkedList<Integer> list = new LinkedList<>();
while(node != null){
list.add(0, node.val);
node = map.get(node);
}
res.add(list);
}