题解 | #牛的奶量统计II#
牛的奶量统计II
https://www.nowcoder.com/practice/9c56daaded6b4ba3a9f93ce885dab764
题目考察的知识点是:
本题主要考察二叉树知识。
题目解答方法的文字分析:
首先判断根节点是否为空。随后构建递归函数来判断当前节点是否满足路径和等于给定值。并且不断调用hasPathSumII函数来递归判断当前节点的子树中是否存在该路径。
本题解析所用的编程语言:
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 targetSum int整型
* @return bool布尔型
*/
public boolean hasPathSumII (TreeNode root, int targetSum) {
// write code here
if (root == null) {
return false;
}
return hasPath(root, targetSum) ||
hasPathSumII(root.left, targetSum) ||
hasPathSumII(root.right, targetSum);
}
public boolean hasPath (TreeNode root, int targetSum) {
// write code here
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return root.val == targetSum;
}
return hasPath(root.left, targetSum - root.val) ||
hasPath(root.right, targetSum - root.val);
}
}
#题解#
顺丰集团工作强度 315人发布
查看20道真题和解析