示例代码

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    public int help (TreeNode root, int sum) {
        if (root == null) {
            return 0;
        }
        int count = sum - root.val == 0 ? 1 : 0;
        count += help(root.left, sum - root.val);
        count += help(root.right, sum - root.val);
        return count;
    }
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类
     * @param sum int整型
     * @return int整型
     */
    public int FindPath (TreeNode root, int sum) {
        // write code here
        // 递归查找以左孩子为起点的路径数
        // int leftPaths = FindPath(root.left, sum);
        // // 递归查找以右孩子为起点的路径数
        // int rightPaths = FindPath(root.right, sum);
        // // 在当前节点调用help函数,检查以当前节点为起点的路径数
        // int rootPaths = help(root, sum);
        // // 将三部分的路径数加起来,返回这个总和
        return root != null ? FindPath(root.left, sum) + FindPath(root.right,
                sum) + help(root, sum) : 0;
    }
}

效果展示

LeetCode---JZ84 二叉树中和为某一值的路径(三)_算法