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

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

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

//采用两层递归循环来解决问题

public class Solution {

public int sumOfPath = 0;
public int FindPath (TreeNode root, int sum) {
    // write code here
    if(root==null){
        return 0;
    }
    computePath(root,sum);
    return sumOfPath;
}

public void computePath(TreeNode root, int sum){
    computeFindPath(root,0,sum);
    if(root.left!=null){
        computePath(root.left,sum);
    }
    if(root.right!=null){
        computePath(root.right,sum);
    }
}

private void computeFindPath(TreeNode root, int sum,int target) {
    if(root==null){
        return;
    }
    sum+= root.val;
    if(sum==target){
        sumOfPath++;
    }
    computeFindPath(root.left,sum,target);
    computeFindPath(root.right,sum,target);
}

}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务