题解 | #牛群特殊路径的数量#
牛群特殊路径的数量
https://www.nowcoder.com/practice/1c0f95d8396a432db07945d8fe51a4f5
题目考察的知识点
考察二叉树的深度优先遍历
题目解答方法的文字分析
题目有迷惑性,路径必须从上到下,意思是说不必从根节点开始一直到叶子节点,只要满足从上到下就可以。
解题思路是自上而下,使用深度优先搜索遍历每一个节点的所有路径可能。
本题解析所用的编程语言
使用Java解答
完整且正确的编程代码
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 res = search(root,sum);
res += pathSum(root.left,sum);
res += pathSum(root.right, sum);
return res;
}
public int search(TreeNode root, int sum) {
int total = 0;
if (root == null) return 0;
if (sum == root.val) {
total ++;
}
total+=search(root.left, sum-root.val);
total+=search(root.right, sum-root.val);
return total;
}
}
#面试高频TOP202#
