educative.io

Count can be done with O(n) without backtracking

const ZERO = 0;
const ONE = 1;

/**
*

  • @param root
  • @param requiredSum
  • returns count of possible paths
    */

const allPathsSum = (root: TTreeNode, requiredSum: number ): number => {
if (root === null) {
return ZERO;
}
if (requiredSum === root.value && root.left === null && root.right === null) {
return ONE;
}
return (
allPathsSum(root.left, requiredSum - root.value) +
allPathsSum(root.right, requiredSum - root.value)
);
}