题解 | #二叉树中和为某一值的路径(三)#
二叉树中和为某一值的路径(三)
https://www.nowcoder.com/practice/965fef32cae14a17a8e86c76ffe3131f
/*class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param sum int整型 * @return int整型 */ export function FindPath(root: TreeNode, sum: number): number { // write code here if (root === null) return 0 let count = 0 // compute current node const pathCount = (root: TreeNode, sum: number): number => { if (root === null) return 0 const rest = sum - root.val if (rest === 0) { count++ } const leftCount = pathCount(root.left, rest) const rightCount = pathCount(root.right, rest) return count + leftCount + rightCount } // compute every node const allPath = (root: TreeNode, sum: number): number => { if (root === null) return pathCount(root, sum) allPath(root.left, sum) allPath(root.right, sum) } allPath(root, sum) return count }