题目:
给定一个二叉树,它的每个结点都存放着一个整数值。
找出路径和等于给定数值的路径总数。
路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
10
/ \
5 -3
/ \ \
3 2 11
/ \ \
3 -2 1
返回 3。和等于 8 的路径有:
1. 5 -> 3
2. 5 -> 2 -> 1
3. -3 -> 11
题解:
import java.util.*;
class TreeNode {
int val;
TreeNode left = null;
TreeNode right = null;
TreeNode (int val) {
this.val = val;
}
}
//快速对齐快捷键是Ctrl+Alt+L
class Solution {
public int pathSum(TreeNode root, int sum) {
if (root == null) {
return 0;
}
return calPathSum(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
private int calPathSum(TreeNode root, int sum) {
if (root == null) {
return 0;
}
int count = 0;
sum = sum - root.val;
if (sum == 0) {//sum == 0啊
count++;
}
return count + calPathSum(root.left, sum) + calPathSum(root.right, sum);
}
}
public class Main {
public static void main(String[] args) {
int sum = 8;
TreeNode root = new TreeNode(10);
root.left = new TreeNode(5);
root.left.left = new TreeNode(3);
root.left.left.left = new TreeNode(3);
root.left.left.right = new TreeNode(-2);
root.left.right = new TreeNode(2);
root.left.right.right = new TreeNode(1);
root.right = new TreeNode(-3);
root.right.right = new TreeNode(11);
Solution p = new Solution();
int res = p.pathSum(root, sum);
System.out.println("结果:" + res);
}
}