题目原文:
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]
]
题目大意:
给出一个二叉树和目标和值,输出从根节点到叶子节点的路径为目标和值的所有路径。
题目分析:
还是一个回溯法,backtrack(List<List<Integer>> list, List<Integer> sublist, TreeNode root, int sum)
维护搜索过程,其中sum记录还剩下的和值,如果sum恰好为当前节点值且当前节点是叶子节点(想想为什么不能是root==null的时候停止?这样每个路径会添加两遍),则停止搜索,否则递归向子树搜索。
源码:(language:java)
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
if(root!=null)
backtrack(list, new ArrayList<Integer>(), root, sum);
return list;
}
private void backtrack(List<List<Integer>> list, List<Integer> sublist, TreeNode root, int sum) {
sublist.add(root.val);
if(sum-root.val == 0 && root.left == null && root.right == null)
list.add(new ArrayList<Integer>(sublist));
if(root.left!=null)
backtrack(list, sublist, root.left, sum-root.val);
if(root.right!=null)
backtrack(list, sublist, root.right, sum-root.val);
sublist.remove(sublist.size()-1);
}
}
成绩:
3ms,beats 14.57%,众数3ms,51.99%