All files / leetCode 0112.ts

100% Statements 14/14
100% Branches 14/14
100% Functions 2/2
100% Lines 14/14

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            5x       12x 6x   6x 5x 5x 2x     4x 3x 3x 2x       5x 1x 4x    
import type { TreeNode } from './Tree'
 
export default function hasPathSum(
  root: TreeNode<number> | null,
  targetSum: number,
): boolean {
  const dfs = (
    node: TreeNode<number>,
    currSum: number,
  ): boolean | undefined => {
    if (node.left === null && node.right === null)
      return currSum === targetSum
 
    if (node.left) {
      const leftSum = currSum + node.left.val
      if (dfs(node.left, leftSum))
        return true
    }
 
    if (node.right) {
      const rightSum = currSum + node.right.val
      if (dfs(node.right, rightSum))
        return true
    }
  }
 
  if (root === null)
    return false
  return Boolean(dfs(root, root.val))
}