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
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if(root == null) return result; ArrayList<Integer> output = new ArrayList<Integer>(); int curSum = 0; generate(curSum, sum, root, output, result); return result; } private void generate(int curSum, int target, TreeNode root, ArrayList<Integer> output, ArrayList<ArrayList<Integer>> result){ curSum += root.val; output.add(root.val); Boolean isLeaf = (root.left == null && root.right == null); if(curSum == target && isLeaf){ ArrayList<Integer> tmp = new ArrayList<Integer>(); tmp.addAll(output); result.add(tmp); // 删掉一个的原因是还要去check该node的sibling output.remove(output.size() - 1); return; } if(root.left != null){ generate(curSum, target, root.left, output, result); } if(root.right != null){ generate(curSum, target, root.right, output, result); } output.remove(output.size() - 1); } }