Clean backtracking Java solution


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

  • 0
    K
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.