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

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

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

需要遍历所有节点 前序遍历时进行判断该节点是个否满足

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param root TreeNode类 
 * @param sum int整型 
 * @return int整型
 */
let res=0
function FindPath( root ,  sum ) {
    // write code here
    if(!root) {
        return 0
    }
    dfs(root,sum)
    FindPath(root.left,sum)
    FindPath(root.right,sum)
    return res
}
function dfs(node,sum){
    if(!node){return }
    sum-=node.val
    if(sum===0) {res+=1}
    dfs(node.left,sum)
    dfs(node.right,sum)
    
}
module.exports = {
    FindPath : FindPath
};
全部评论

相关推荐

团子 行业运营 n*15.5
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务