113. 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.

For example: Given the below binary tree and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    List<List<Integer>> res = new ArrayList<>();    
    public List<List<Integer>> pathSum(TreeNode root, int sum) {

        getSum(root, new ArrayList<Integer>(), 0, sum);
        return res;
    }

    private void getSum(TreeNode node, List<Integer> list, int current, int sum){
        if(node == null) return;
        current += node.val;
        list.add(node.val);

        if(node.left == null && node.right == null){
            if(current == sum){
                res.add(list);
            }else{
                return;
            }
        }
        if(node.left != null){
            getSum(node.left, new ArrayList<Integer>(list), current, sum);
        }
        if(node.right != null){
            getSum(node.right, new ArrayList<Integer>(list), current, sum);

        }

    }

}
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        if(root == null) return res;
        build(root, new ArrayList<Integer>(), 0, sum);
        return res;
    }

    void build(TreeNode root, List<Integer> list, int cur, int target){
        if(root.left == null && root.right == null){
            if(cur + root.val == target){
                list.add(root.val);
                res.add(new ArrayList<>(list));
                list.remove(list.size()-1);
            }
            return;
        }
        list.add(root.val);
        if(root.left != null) build(root.left, list, cur+root.val, target);
        if(root.right != null) build(root.right, list, cur + root.val, target);
        list.remove(list.size()-1);
    }
}

results matching ""

    No results matching ""