题解 | #二叉树中和为某一值的路径(三)#
二叉树中和为某一值的路径(三)
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整型 */ let res = 0 const dfs = (root:TreeNode,sum:number)=>{ if(root === null){ return res } if(sum === root.val){ res++ } //在子节点中继续寻找 dfs(root.left,sum-root.val) dfs(root.right,sum-root.val) } export function FindPath(root: TreeNode, sum: number): number { // write code here //1.每个节点都有可能作为根节点,去找这个路径 //2.把每一个节点作为根查询路径它的路径书 //3.一个函数来遍历所有的节点节点作为 if(root === null)return res //查询路径 dfs(root,sum) FindPath(root.left,sum) FindPath(root.right,sum) return res }