题目:牛客网

解题思路:

只有当节点为叶子节点且root到leaf的和等于sum才是符合题意得路径

即加入res的条件一定是node.left==null && node.right==null && node.val == sum-(root到node的父节点的和)

使用递归

import java.util.ArrayList;
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
        ArrayList<ArrayList<Integer>> res = new ArrayList();
        if (root == null) return res;
        helper(root, sum, new ArrayList(), res);
        return res;
    }
     
    public void helper(TreeNode root, int sum, ArrayList<Integer> cur, ArrayList<ArrayList<Integer>> res) {
        if (root == null) return;
         
        if (root.left == null && root.right == null) {
            if (sum == root.val) {
                ArrayList<Integer> tmp = new ArrayList();
                tmp.addAll(cur);
                tmp.add(root.val);
                res.add(tmp);
            }
        }
         
        cur.add(root.val);
        helper(root.left, sum - root.val, cur, res);
        helper(root.right, sum - root.val, cur, res);
        cur.remove(cur.size() - 1);
    }
}