Description
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]
]
问题描述
给定二叉树和sum, 找出所有根节点到叶子节点的路径, 这些路径上的所有节点之和等于sum
问题分析
解法
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList();
if(root == null) return res;
findPath(root, res, new ArrayList(), sum);
return res;
}
public void findPath(TreeNode root, List<List<Integer>> res, List<Integer> line, int sum){
line.add(root.val);
sum -= root.val;
if(root.left == null && root.right == null && sum == 0) res.add(new ArrayList(line));
if(root.left != null) findPath(root.left, res, line, sum);
if(root.right != null) findPath(root.right, res, line, sum);
line.remove(line.size() - 1);
}
}