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

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

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

Java-递归

import java.util.*;
public class Solution {
    // 计算以root为根的树中路径和为sum的路径总数
    public int FindPath(TreeNode root, int sum) {
        // write code here
        if (root == null) {
            return 0;
        }
        int startAtRoot = Find(root, sum, 0);
        int l = FindPath(root.left, sum);
        int r = FindPath(root.right, sum);
        return l + r + startAtRoot;
    }
    // 计算以root为起点,到其某个子节点的路径和为sum的路径数
    public int Find(TreeNode root, int sum, int temp) {
        if (root == null) {
            return 0;
        }
        int count = 0;
        if (sum == temp + root.val) {
            count = 1;
        }
        temp += root.val;
        int l = Find(root.left, sum, temp);
        int r = Find(root.right, sum, temp);
        return l + r + count;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
07-02 10:39
门头沟学院 Java
Steven267:说点真实的,都要秋招了,还没有实习,早干嘛去了,本来学历就差,现在知道急了,而且你这个简历完全可以写成一页,劣势太大了,建议转测试
点赞 评论 收藏
分享
今天 18:35
湖南大学 C++
投递拼多多集团-PDD等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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