Enter a binary tree and an integer, and print out the sum of node values in the binary tree as all paths to the input integers. A path is formed from the root of the tree down to the nodes passed by the leaf.
Example: Given the following binary tree with the target and sum = 22,
java
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; }} * * /
class Solution {
LinkedList<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
recurr(root,sum);
return res;
}
void recurr(TreeNode root, int sum){
if(root==null) return ;
path.add(root.val);
sum = sum - root.val;
if(sum==0&&root.left==null&&root.right==null){
res.add(newLinkedList(path)); } recurr(root.left,sum); recurr(root.right,sum); path.removeLast(); }}Copy the code