Straight forward DFS 2ms

  • 0
     public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> result = new ArrayList<>();
            dfs(root, sum, new ArrayList<Integer>(), result);
            return result;
        public void dfs(TreeNode root, int sum, List<Integer> current, List<List<Integer>> result) {
            if (root == null) return;
            sum -= root.val;
            if (root.left == null && root.right == null) {
                if (sum == 0) {
                    result.add(new ArrayList<>(current));
            dfs(root.left, sum, current, result);
            dfs(root.right, sum, current, result);

Log in to reply

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