Path Sum II
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
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]
]
This problem is kind of similar but harder that the path sum I proglem. And I firstly just use a very brutal force solution. I print out all the path from root to leaf in the tree, and then I check each path's sum. If that equals to expected sum, keep it. Else
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { if (root == null) return null; ArrayList<Integer> path = new ArrayList<Integer>(); ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>(); resultList = getAllPath(root, path, resultList); //printResult(resultList); return filterResultList(resultList, sum); //return null; } public ArrayList<ArrayList<Integer>> getAllPath(TreeNode root, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> resultList ){ if (root == null) return null; path.add(root.val); if (root.left == null && root.right == null){ //System.out.println(path); resultList.add(path); return resultList; } getAllPath(root.left, new ArrayList<Integer>(path), resultList); getAllPath(root.right, new ArrayList<Integer>(path), resultList); return resultList; } public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, ArrayList<ArrayList<Integer>> resultList){ if (root == null) return null; resultList.get(resultList.size()-1).add(root.val); if (root.left != null){ ArrayList<ArrayList<Integer>> tempList = resultList; tempList = pathSum(root.left, tempList); } if (root.right != null){ ArrayList<Integer> nestList = resultList.get(resultList.size()-1); resultList.add(nestList); resultList = pathSum(root.right, resultList); } return resultList; } public ArrayList<ArrayList<Integer>> filterResultList(ArrayList<ArrayList<Integer>> resultList, int sum){ for (int i = 0; i < resultList.size(); i ++){ int realSum = 0; for (int element: resultList.get(i)){ realSum += element; //System.out.println(element); } if (realSum != sum) resultList.remove(i); } return resultList; } public void printResult(ArrayList<ArrayList<Integer>> resultList){ for (ArrayList<Integer> nestResult : resultList){ for (int element : nestResult){ System.out.print(element + " "); } System.out.println(""); } } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public static void main(String[] args){ solution obj = new solution(); TreeNode h = obj.new TreeNode(1); TreeNode a = obj.new TreeNode(-2); TreeNode b = obj.new TreeNode(-3); TreeNode c = obj.new TreeNode(1); TreeNode d = obj.new TreeNode(3); TreeNode f = obj.new TreeNode(1); TreeNode e = obj.new TreeNode(3); h.left = a; h.right = b; a.left = c; a.right = d; c.left = f; b.left = e; //obj.pathSum(h, 2); obj.printResult(obj.pathSum(h, 1)); }