113.Path Sum II

When find a path, we need to new a 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>> ans = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        findPath(ans, path, root, sum);
        return ans;
    }

    public void findPath(List<List<Integer>> ans, List<Integer> path, TreeNode root, int remainSum){
        if(root == null){
            return;
        }
        else{
            path.add(root.val);
            if(root.left == null && root.right == null && root.val == remainSum){
                ans.add(new ArrayList(path));
                path.remove(path.size() -1);
                return;
            }
            else{
                findPath(ans, path, root.left, remainSum - root.val);
                findPath(ans, path, root.right, remainSum - root.val);
                path.remove(path.size() -1);
                return;
            } 
        }
    }
}

results matching ""

    No results matching ""