All files / leetCode 0113.ts

100% Statements 13/13
100% Branches 11/11
100% Functions 2/2
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31            6x   6x         18x 4x 4x     14x 14x   14x 14x     6x 1x 5x 5x    
import type { TreeNode } from './Tree'
 
export default function pathSum(
  root: TreeNode<number> | null,
  targetSum: number,
): number[][] {
  const paths: number[][] = []
 
  const dfs = (
    node: TreeNode<number>,
    currSum: number,
    path: number[],
  ): void => {
    if (node.left === null && node.right === null && currSum === targetSum) {
      paths.push(path)
      return
    }
 
    if (node.left)
      dfs(node.left, currSum + node.left.val, path.concat(node.left.val))
 
    if (node.right)
      dfs(node.right, currSum + node.right.val, path.concat(node.right.val))
  }
 
  if (root === null)
    return paths
  dfs(root, root.val, [root.val])
  return paths
}