题解 | #二叉树中和为某一值的路径(三)#

二叉树中和为某一值的路径(三)

https://www.nowcoder.com/practice/965fef32cae14a17a8e86c76ffe3131f

因为这道题并不是这条他们之和的路径一定包含根路径,可以是这棵树的局部路径

  1. 每个节点都可以是该条路径的根节点,所以需要对每一个节点作为根节点寻找路径
  2. 需要一个寻找路径的函数
  3. 需要一个遍历每一个节点的函数
/*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
}

全部评论

相关推荐

04-23 10:44
已编辑
门头沟学院 Java
pdd
爱吃鱼的肖恩求实习:pdd感觉池子太深了,hr面一周了没消息
点赞 评论 收藏
分享
03-26 13:44
南华大学 Java
在看面经的花生米很野蛮:这种情况下你当然要回答,你也是吗!!!!我超喜欢他的XXXXX
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务