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

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

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

import java.util.*;


public class Solution {

    int res = 0;
    // 该题路径定义:不需要从根节点开始,也不需要在叶子结点结束
    // 遍历每一棵树及子树
    public int FindPath (TreeNode root, int sum) {
        // write code here
        if(root == null){
            return res;
        }
        // 查询以某节点为根的路径数
        dfs(root,sum);

        // 再以子节点为根,遍历整棵树
        FindPath(root.left,sum);
        FindPath(root.right,sum);

        return res;
    }

    public void dfs(TreeNode root, int sum){
        if(root == null) return;
        if(sum - root.val == 0){
            res++;
        }
        dfs(root.left,sum - root.val);
        dfs(root.right,sum - root.val);
    }
}

全部评论

相关推荐

仁者伍敌:实习生要工作经验,工作要实习经验
点赞 评论 收藏
分享
07-15 16:52
已编辑
门头沟学院 Java
周五投的,流程今天结束
投递地平线等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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