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);
    }
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Mandy Lin

    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;

    }

    }

  • Burhan COKCA

    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;
    }
    }