题解 | #牛群特殊路径的数量#
牛群特殊路径的数量
https://www.nowcoder.com/practice/1c0f95d8396a432db07945d8fe51a4f5
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 {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param sum int整型
* @return int整型
*/
public int pathSum (TreeNode root, int sum) {
// write code here
if(root==null){
return 0;
}
int count = 0;
count += search(root, sum);
count += pathSum(root.left, sum);
count += pathSum(root.right, sum);
return count;
}
public int search(TreeNode root, int target) {
if (root == null) {
return 0;
}
int total = 0;
if (root.val == target) {
total++;
}
total += search(root.left, target - root.val);
total += search(root.right, target - root.val);
return total;
}
}
本题考察的知识点是二叉树,所用编程语言是java。
首先我们需要明确题目意思,题目是需要找一条从上至下的路径,那么就不存在一条路径既包含某一节点的左节点也包含右节点。比如某条路径含有一个既有左子树又有右子树的分支结点,那么我们则需要看该左子树有多少条和sum-root.val的路径和右子树有多少条和为sum-root.val的路径。我们对该二叉树进行前序遍历,遍历到某个节点时,判断含有该节点等于目标值的路径有多少条,对所有路径数进行累加得出答案