Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22
,
5 / 4 8 / / 11 13 4 / / 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
dfs method:
public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer> > paths = new ArrayList<List<Integer>>(); List<Integer> oneSolution = new ArrayList<Integer>(); if(root != null) dfs(root, 0, sum, oneSolution, paths); return paths; } private void dfs(TreeNode node, int accu, int sum, List<Integer> oneSolution, List<List<Integer>> paths) { accu += node.val; oneSolution.add(node.val); if(node.left == null && node.right == null && accu == sum) { List<Integer> copy = new ArrayList<Integer>(); copy.addAll(oneSolution); paths.add(copy); } else{ if(node.left != null) dfs(node.left, accu, sum, oneSolution, paths); if(node.right != null) dfs(node.right, accu, sum, oneSolution, paths); } accu -= node.val; oneSolution.remove(oneSolution.size() - 1); } }
bfs method:
public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer> > result = new ArrayList<List<Integer> >(); Map<TreeNode, List<Integer> > fromTreeNodeToList = new HashMap<TreeNode, List<Integer> >(); Map<TreeNode, Integer> fromTreeNodeToSum = new HashMap<TreeNode, Integer>(); if(root != null){ Deque<TreeNode> nodes = new LinkedList<TreeNode>(); nodes.add(root); List<Integer> startList = new ArrayList<Integer>(); startList.add(root.val); fromTreeNodeToList.put(root, startList); fromTreeNodeToSum.put(root, root.val); while(nodes.peek() != null){ TreeNode aNode = nodes.poll(); if(aNode.left == null && aNode.right == null){ if(fromTreeNodeToSum.get(aNode) == sum) result.add(fromTreeNodeToList.get(aNode)); } else{ int sumAtNode = fromTreeNodeToSum.get(aNode); List<Integer> listAtNode = fromTreeNodeToList.get(aNode); if(aNode.left != null){ List<Integer> newList = new ArrayList<Integer>(); newList.addAll(listAtNode); newList.add(aNode.left.val); fromTreeNodeToSum.put(aNode.left, sumAtNode + aNode.left.val); fromTreeNodeToList.put(aNode.left, newList); nodes.add(aNode.left); } if(aNode.right != null){ List<Integer> newList = new ArrayList<Integer>(); newList.addAll(listAtNode); newList.add(aNode.right.val); fromTreeNodeToSum.put(aNode.right, sumAtNode + aNode.right.val); fromTreeNodeToList.put(aNode.right, newList); nodes.add(aNode.right); } } } } return result; } }