给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
说明: 叶子节点是指没有子节点的节点。
示例:
给定如下二叉树,以及目标和 sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
返回:
[ [5,4,11,2], [5,8,4,5] ]
解题思路:
深度优先搜索DFS,只不过数据结构相对复杂一点,需要用到嵌套的列表,而且每当DFS搜索到新节点时,都要保存该节点。而且每当找出一条路径之后,都将这个当前列表保存到最终结果的嵌套列表中。并且,当搜索完当前节点的左右子树时,需要把当前节点从列表中移除,或者搜索到子节点,发现是所求路径时,同样把当前节点从列表中移除,进行下一轮路径的判断。
public static List<List<Integer>> pathSum(TreeNode root, int sum)
{
List<List<Integer>> result = new LinkedList<List<Integer>>();
List<Integer> currentResult = new LinkedList<Integer>();
pathSum(root,sum,currentResult,result);
return result;
}
public static void pathSum(TreeNode root, int sum, List<Integer> currentResult,List<List<Integer>> result)
{
if (root == null)
return;
currentResult.add(new Integer(root.val));
if (root.left == null && root.right == null && sum == root.val)
{
result.add(new LinkedList(currentResult));
currentResult.remove(currentResult.size() - 1);//don't forget to remove the last integer
return;
}
else
{
pathSum(root.left, sum - root.val, currentResult, result);
pathSum(root.right, sum - root.val, currentResult, result);
}
currentResult.remove(currentResult.size() - 1);
}