题解 | #牛的奶量统计#
牛的奶量统计
https://www.nowcoder.com/practice/213c039668804add9513bbee31370248
public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param targetSum int整型 * @return bool布尔型 */ int now=0;//定义一个全局的变量 public boolean hasPathSum (TreeNode root, int targetSum) { // write code here if(root==null&& targetSum==0) return false; now=now+root.val; if(root.left==null&&root.right==null){ if(now==targetSum) return true; else { now=now-root.val;//回溯 return false; } } if(root.left!=null){//在左子树找 boolean left=hasPathSum(root.left,targetSum); if(left) return true; } if(root.right!=null){//在右子树找 boolean right=hasPathSum(root.right,targetSum); if(right) return true; } now=now-root.val;//都没找到要回溯 return false; }