Java,backtrack, clean, easy understood


  • 1
    J
    public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<Integer>();
        doSearch(res, temp, root, sum);
        return res;
    }
    private void doSearch(List<List<Integer>> res, List<Integer> temp, TreeNode root, int sum) {
        if(root == null) {
            return;
        }
        sum -= root.val;
        temp.add(root.val);
        if(sum == 0 && root.left == null && root.right == null) {
            res.add(new ArrayList<Integer>(temp));
        }
        doSearch(res, temp, root.left, sum);
        doSearch(res, temp, root.right, sum);
        temp.remove(temp.size() - 1);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.