Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
Note: A leaf is a node with no children.
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]
]
给出一个二叉树,让返回所有root-to-leaf 路径,满足路径上节点值的和=sum
注意是root to leaf 路径,中间即使和=sum,如果不到leaf节点,也不算满足
思路:
因为要找出所有路径,所以用DFS遍历所有路径
判断和=sum时一定要判断是不是leaf节点
另外注意DFS中一个节点遍历完后从path中remove掉时,要直接remove掉最后一个即可,不能按值remove,比如path.remove(new Integer(1))
如果按值remove,会有一个后果,比如path中存了[1,2,1], 本意是remove最后一个1,然而按值remove的话会把第一个1 remove掉,路径讲究顺序,顺序不同也是会WA的
//1ms, 100%(current time)
private int addSum = 0;
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<Integer>();
dfs(root, path, sum, result);
return result;
}
public void dfs(TreeNode root, List<Integer> path, int sum, List<List<Integer>> result) {
if (root == null) {
return;
}
addSum += root.val;
path.add(root.val);
if (addSum == sum && root.left == null && root.right == null) {
List<Integer> tmpPath = new ArrayList<Integer>(path);
result.add(tmpPath);
addSum -= root.val;
path.remove(path.size() - 1);
return;
}
dfs(root.left, path, sum, result);
dfs(root.right, path, sum, result);
addSum -= root.val;
path.remove(path.size() - 1);
}