LeetCode – Path Sum II (Java)

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

the method returns the following:

[
   [5,4,11,2],
   [5,8,4,5]
]

Analysis

This problem can be converted to be a typical depth-first search problem. A recursive depth-first search algorithm usually requires a recursive method call, a reference to the final result, a temporary result, etc.

Java Solution

public List<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
    ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
    if(root == null) 
        return result;
 
    ArrayList<Integer> l = new ArrayList<Integer>();
    l.add(root.val);
    dfs(root, sum-root.val, result, l);
    return result;
}
 
public void dfs(TreeNode t, int sum, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> l){
    if(t.left==null && t.right==null && sum==0){
        ArrayList<Integer> temp = new ArrayList<Integer>();
        temp.addAll(l);
        result.add(temp);
    }
 
    //search path of left node
    if(t.left != null){
        l.add(t.left.val);
        dfs(t.left, sum-t.left.val, result, l);
        l.remove(l.size()-1);
    }
 
    //search path of right node
    if(t.right!=null){
        l.add(t.right.val);
        dfs(t.right, sum-t.right.val, result, l);
        l.remove(l.size()-1);
    }
}

5 thoughts on “LeetCode – Path Sum II (Java)”


  1. public LinkedList<LinkedList> rootToLeafSum(BTNode root, int sum) {
    if (root == null)
    return null;
    LinkedList<LinkedList> paths = new LinkedList();
    LinkedList currentPath = new LinkedList();
    rootToLeafSum(root, paths, currentPath, sum - root.data);
    return paths;
    }

    @SuppressWarnings("unchecked")
    private void rootToLeafSum(BTNode node, LinkedList<LinkedList> paths, LinkedList path, int sum) {
    if (node.right == null && node.left == null && sum == 0) {
    path.add(node);
    paths.add(path);
    return;
    }
    path.add(node);
    if (node.left != null) {
    rootToLeafSum(node.left, paths, (LinkedList) path.clone(), sum - node.left.data);
    }
    if (node.right != null) {
    rootToLeafSum(node.right, paths, (LinkedList) path.clone(), sum - node.right.data);
    }
    }

  2. public boolean hasPathSum(TreeNode root, int sum) {
    if(root ==null){
    return false;
    }
    boolean hasSum = sumHelper(root,0,sum);
    return hasSum;
    }

    public boolean sumHelper(TreeNode node,int runningSum,int sum){
    if(node ==null){
    return false;
    }
    if(node.left == null && node.right ==null){
    runningSum+=node.val;
    return (runningSum == sum);
    }
    runningSum += node.val;
    return sumHelper(node.left,runningSum,sum) || sumHelper(node.right,runningSum,sum);
    }

  3. Here is my solution:

    void findPaths(Node* root, int sum, vector cur, vector<vector>& results)
    {
    if(root == NULL) return ;

    cur.push_back(root->val);

    if(root->val == sum && root->left == NULL && root->right == NULL)
    { results.push_back(cur); return ;}

    findPaths(root->left, sum-root->val, cur, results);
    findPaths(root->right, sum-root->val, cur, results);

    }

  4. I wrote a solution but it was wrong. Someone could help?

    /**

    * Definition for a binary tree node.

    * public class TreeNode {

    * int val;

    * TreeNode left;

    * TreeNode right;

    * TreeNode(int x) { val = x; }

    * }

    */

    public class Solution {

    public List<List> pathSum(TreeNode root, int sum) {

    List<List> list = new ArrayList();

    List sublist = new ArrayList();

    Record record = new Record(0, sublist);

    record = DFS(root, sum, record);

    if(record.hasPath()) {

    list.add(record.getList());

    }

    return list;

    }

    public Record DFS(TreeNode node, int sum, Record record) {

    if(node == null) {

    return null;

    }

    if(node.left == null && node.right == null) {

    if(record.getVal() + node.val == sum) {

    record.hasPath();

    record.add(node.val);

    return record;

    } else {

    return record;

    }

    }

    record.hasPath();

    record.add(node.val);

    record.updateVal(node.val);

    return (DFS(node.left, sum, record) || DFS(node.right, sum, record));

    //return DFS(node.left, sum, record);

    }

    }

    class Record {

    private int calculatedVal;

    private List sublist;

    private boolean foundPath;

    public Record(int c, List s) {

    this.calculatedVal = c;

    this.sublist = s;

    this.foundPath = false;

    }

    public int getVal() {

    return calculatedVal;

    }

    public void updateVal(int val) {

    calculatedVal += val;

    }

    public List getList() {

    return sublist;

    }

    public void add(int val) {

    sublist.add(val);

    }

    public boolean hasPath() {

    foundPath = true;

    return foundPath;

    }

    }

  5. It still can be solved with bfs. By using the Path Sum solution, you will need extra list collections and a queue to store the lists while you traversing

    public class Solution {
    public List<List> pathSum(TreeNode root, int sum) {
    List<List> result = new ArrayList<List>();
    if(root == null) return result;
    LinkedList nodes = new LinkedList();
    LinkedList sumValues = new LinkedList();

    nodes.add(root);
    sumValues.add(root.val);

    LinkedList<List> l = new LinkedList<List>();
    List a = new ArrayList();
    a.add(root.val);
    l.add(a);

    while(!nodes.isEmpty()){

    Integer sumValue = sumValues.poll();
    TreeNode t = nodes.poll();
    a = l.poll();

    if(t.left == null && t.right == null && sumValue == sum){
    result.add(a);
    }
    else{
    if(t.right != null) {
    nodes.add(t.right);
    sumValues.add(t.right.val + sumValue);
    List r = new ArrayList();
    r.addAll(a);
    r.add(t.right.val);
    l.add(r);
    }

    if(t.left != null) {
    nodes.add(t.left);
    sumValues.add(t.left.val + sumValue);
    List le = new ArrayList();
    le.addAll(a);
    le.add(t.left.val);
    l.add(le);
    }
    }
    }
    return result;
    }
    }

Leave a Comment