Path Sum II

题目
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

答案

class Solution {
    public List> pathSum(TreeNode root, int sum) {
        List> list = new ArrayList>();
        List curr = new ArrayList<>();
        recur(root, sum, list, curr, 0);
        return list;
    }
    
    private void recur(TreeNode root, int sum, List> list, List curr, int curr_sum) {
        if(root == null) return;
        if(root.left == null && root.right == null) {
            if(sum == curr_sum + root.val) {
                List newlist = new ArrayList<>(curr);
                newlist.add(root.val);
                list.add(newlist);
            }
            return;
        }
        
        curr.add(root.val);
        recur(root.left, sum, list, curr, curr_sum + root.val);
        recur(root.right, sum, list, curr, curr_sum + root.val);
        curr.remove(curr.size() - 1);
    }
}

你可能感兴趣的:(Path Sum II)