题解 | #牛的奶量统计II#
牛的奶量统计II
https://www.nowcoder.com/practice/9c56daaded6b4ba3a9f93ce885dab764
使用深度遍历的思路,从上往下传上面的节点值,
并用递归进行调用
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 hasCurrentPathSumII(root, targetSum, root.val);
}
public boolean hasCurrentPathSumII (TreeNode root, int targetSum, int parentSum) {
// write code here
if (root.left != null) {
int currentSum = root.left.val + parentSum;
if (currentSum == targetSum) {
return true;
}
if (root.left.val == targetSum) {
return true;
}
if (hasCurrentPathSumII(root.left, targetSum, currentSum)) {
return true;
}
if (hasCurrentPathSumII(root.left, targetSum, 0)) {
return true;
}
}
if (root.right != null) {
int currentSum = root.right.val + parentSum;
if (currentSum == targetSum) {
return true;
}
if (root.right.val == targetSum) {
return true;
}
if (hasCurrentPathSumII(root.right, targetSum, currentSum)) {
return true;
}
if (hasCurrentPathSumII(root.right, targetSum, 0)) {
return true;
}
}
return false;
}
}
