题解 | #牛的奶量统计#

牛的奶量统计

https://www.nowcoder.com/practice/213c039668804add9513bbee31370248?tpId=354&tqId=10591582&ru=/exam/oj/ta&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D354

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 hasPathSum (TreeNode root, int targetSum) {
    // 如果根节点为空,直接返回 false
    if(root == null) return false;
    // 如果根节点是叶子节点,判断它的值是否等于目标值 这个条件很容易被忽略
    if(root.left == null && root.right == null) return root.val == targetSum;
    // 递归判断左右子树是否有满足条件的路径,只要有一个为 true 就返回 true
    return hasPathSum(root.left,targetSum - root.val) || hasPathSum(root.right,targetSum - root.val);
}

}

这道题的时间复杂度是 O(n),空间复杂度是 O(h),其中 n 是节点个数,h 是树的高度。

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务