Leetcode 113. Path Sum II
题目链接
https://leetcode.com/problems/path-sum-ii/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]
]
题解
递归遍历每一个节点,计算节点的总和,但满足条件的时候就把路径添加到List中。
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> list = new ArrayList<>();
findHelper(root, list, new ArrayList<Integer>(), sum);
return list;
}
public void findHelper(TreeNode root, List<List<Integer>> list, List<Integer> tempList,int sum) {
if (root == null) { return ; }
tempList.add(root.val);
if (root.left == null && root.right == null && sum == root.val) {
list.add(new ArrayList<>(tempList));
}
findHelper(root.left, list, tempList, sum - root.val);
findHelper(root.right, list, tempList, sum - root.val);
tempList.remove(tempList.size() - 1);
}
}