113. Path Sum II (find all root-to-leaf paths where each path's sum equals the given sum.)

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

Note: A leaf is a node with no children.

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]
]


class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res=new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
        dfs(res, temp ,root,sum);
        return res; 
    }
    private void dfs(List<List<Integer>> res, List<Integer> temp, TreeNode node, int sum){
        if (node==null) return;
        temp.add(node.val);
        
        if(node.left==null && node.right==null){
            if (node.val==sum){
               res.add(new ArrayList<>(temp));
               
            }
            temp.remove(temp.size()-1);
            return;
        }else{                       
            dfs(res,temp,node.left,sum-node.val);
            dfs(res,temp,node.right,sum-node.val);
            temp.remove(temp.size()-1);
        }
        
    }
}

 

public List<List<Integer>> pathSum(TreeNode root, int sum){
    // sanity check 
    
    List<List<Integer>> res = new ArrayList<>();
    if(root == null) return res;
    List<Integer> tmp = new ArrayList<>();
    tmp.add(root.val);
    dfs(res, root, sum, tmp);
    return res;
}
private void dfs(List<List<Integer>> res, TreeNode root, int sum, List<Integer> tmp){
    // base case, if the root.val == leftOver num
    if(root.val == sum && root.left == null && root.right == null){
        
        res.add(new ArrayList<>(tmp));
        return;
    }

    // do regular dfs 
    if(root.left != null){
tmp.add(root.left.val);
        dfs(res, root.left, sum - root.val, tmp);
        // backtracking recovery 
        tmp.remove(tmp.size() - 1);
    }

    if(root.right != null){
        tmp.add(root.right.val);
        dfs(res, root.right, sum - root.val, tmp);
        // backtracking recovery 
        tmp.remove(tmp.size() - 1);
    }
}

 

posted on 2018-08-10 14:48  猪猪&#128055;  阅读(125)  评论(0)    收藏  举报

导航