题解 | #牛的奶量统计#

牛的奶量统计

https://www.nowcoder.com/practice/213c039668804add9513bbee31370248

本题考察知识点:二叉树遍历、递归、回溯

解题思路:使用currentSum记录当前路径上的所有节点数值之和,在递归到当前节点时,currentSum加上当前节点的值,递归跳出当前节点时,currentSum再将当前节点值减去。最后到达叶子节点时判断currentSum是否是目标值即可

本题解所用语言: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 {
    int targetSum;
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param targetSum int整型 
     * @return bool布尔型
     */
    public boolean hasPathSum (TreeNode root, int targetSum) {
        // write code here
        this.targetSum = targetSum;
        return checkPath(root, 0);
    }

    public boolean checkPath(TreeNode root, int currentSum) {
        if (root == null) {
            return false;
        }
        currentSum += root.val;
        if (root.left == null && root.right == null) {
            return currentSum == targetSum;
        }
        return checkPath(root.left, currentSum) || checkPath(root.right, currentSum);
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务