原题题目:You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
注意:题目中要求统计路径和等于一个数的路径数量,并且路径不是必须从根节点开始或者以叶子节点结束,也就是还包含从某一节点开始以另一节点结束的路径,但是必须是连续的节点。
- 由于都是想在该节点下进行条件是否满足的判断,以及sum值的变更,因此我们很自然的想到了递归。在当前节点满足等于sum的状况下,就进行路径和数量的加1。
- 由于本题中声明路径不是必须包括根节点和叶子节点,因此我们不能只关注从根节点开始的路径,比如下图:
可以看到有三条路径,因此除了根节点,我们还要从所有的非空节点开始搜索,避免落下每一条路径。
附上代码:
public static int pathSum(TreeNode root, int sum) {
if (root == null)
return 0;
int ret = helper(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
return ret;
}
private static int helper(TreeNode root, int sum) {
if (root == null)
return 0;
int ret = 0;
// 在满足的情况下就+1
if (root.val == sum)
ret++;
ret += helper(root.left, sum - root.val) + helper(root.right, sum - root.val);
System.out.println(root.val + "对应的路径的数目值" + ret);
return ret;
}
public static void main(String[] args) {
TreeNode tree1 = new TreeNode(5);
TreeNode tree2 = new TreeNode(4);
TreeNode tree3 = new TreeNode(11);
TreeNode tree4 = new TreeNode(7);
TreeNode tree5 = new TreeNode(2);
tree1.left = tree2;
tree2.left = tree3;
tree3.left = tree4;
tree3.right = tree5;
System.out.println(pathSum(tree1, 18));
}
附上结果图: