【陪伴式刷题】Day 17|二叉树|112.路径总和(Path Sum) & 113.路径总和ii(Path Sum ii)

刷题顺序按照代码随想录建议

112.路径总和

题目描述

英文版描述

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 Output: true Explanation: The root-to-leaf path with the target sum is shown.

Example 2:

Input: root = [1,2,3], targetSum = 5 Output: false Explanation: There two root-to-leaf paths in the tree: (1 --> 2): The sum is 3. (1 --> 3): The sum is 4. There is no root-to-leaf path with sum = 5.

Example 3:

Input: root = [], targetSum = 0 Output: false Explanation: Since the tree is empty, there are no root-to-leaf paths.

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

英文版地址

leetcode.com/problems/pa...

中文版描述

给你二叉树的根节点 root 和一个表示目标和的整数 targetSum 。判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum 。如果存在,返回 true ;否则,返回 false

叶子节点 是指没有子节点的节点。

示例 1:

输入: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 输出: true 解释: 等于目标和的根节点到叶节点路径如上图所示。

示例 2:

输入: root = [1,2,3], targetSum = 5 输出: false 解释: 树中存在两条根节点到叶子节点的路径: (1 --> 2): 和为 3 (1 --> 3): 和为 4 不存在 sum = 5 的根节点到叶子节点的路径。

示例 3:

输入: root = [], targetSum = 0 输出: false 解释: 由于树是空的,所以不存在根节点到叶子节点的路径。

提示:

  • 树中节点的数目在范围 [0, 5000]
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

中文版地址

leetcode.cn/problems/pa...

解题方法

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        return recursion(root, targetSum);
    }

    private boolean recursion(TreeNode root, int targetSum) {
        if (targetSum- root.val == 0 && root.right == null && root.left == null) {
            return true;
        }
        if (root.right == null && root.left == null) {
            return false;a
        }

        if (root.left != null) {
            if (recursion(root.left, targetSum - root.val)) {
                return true;
            }
        }
        if (root.right != null) {
            if (recursion(root.right, targetSum - root.val)) {
                return true;
            }
        }
        return false;
    }
}

复杂度分析

  • 时间复杂度:O(n),其中 n 是二叉树的节点数,每一个节点恰好被遍历一次
  • 空间复杂度:O(n),为递归过程中栈的开销,平均情况下为 O(log⁡n),最坏情况下树呈现链状,为 O(n)

113.路径总和ii

题目描述

英文版描述

Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum . Each path should be returned as a list of the node values , not node references.

A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.

Example 1:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 Output: [[5,4,11,2],[5,8,4,5]] Explanation: There are two paths whose sum equals targetSum: 5 + 4 + 11 + 2 = 22 5 + 8 + 4 + 5 = 22

Example 2:

Input: root = [1,2,3], targetSum = 5 Output: []

Example 3:

Input: root = [1,2], targetSum = 0 Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 5000].
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

英文版地址

leetcode.com/problems/pa...

中文版描述

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

示例 1:

输入: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 输出: [[5,4,11,2],[5,8,4,5]]

示例 2:

输入: root = [1,2,3], targetSum = 5 输出: []

示例 3:

输入: root = [1,2], targetSum = 0 输出: []

提示:

  • 树中节点的数目在范围 [0, 5000]
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

中文版地址

leetcode.cn/problems/pa...

解题方法

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
     List<List<Integer>> result = new ArrayList<>();
    List<Integer> ll = new ArrayList<>();

    /**
     * 输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
     * 输出:[[5,4,11,2],[5,8,4,5]]
     *
     * @param root
     * @param targetSum
     * @return
     */
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
         if (root == null) {
            return result;
        }
        recursion(root, targetSum);
        return result;
    }

    private void recursion(TreeNode root, int targetSum) {
        ll.add(root.val);
        if (root.left == null && root.right == null && targetSum-root.val == 0) {
            result.add(new ArrayList<>(ll));
            return;
        }
        if (root.left == null && root.right == null) {
            return;
        }
        if (root.left != null) {
            recursion(root.left, targetSum - root.val);
            ll.remove(ll.size() - 1);
        }
        if (root.right != null) {
            recursion(root.right, targetSum - root.val);
            ll.remove(ll.size() - 1);
        }
    }

}

复杂度分析

  • 时间复杂度:O(n),其中 n 是树的节点数。在最坏情况下,树的上半部分为链状,下半部分为完全二叉树,并且从根节点到每一个叶子节点的路径都符合题目要求。此时,路径的数目为 O(n),并且每一条路径的节点个数也为 O(n),因此要将这些路径全部添加进答案中,时间复杂度为 O(n^2)
  • 空间复杂度:O(n),其中 n 是树的节点数,空间复杂度主要取决于栈空间的开销,栈中的元素个数不会超过树的节点数
相关推荐
爱的叹息27 分钟前
spring mvc 中 RestTemplate 全面详解及示例
java·spring·mvc
龙俊杰的读书笔记4 小时前
[leetcode] 面试经典 150 题——篇9:二叉树(番外:二叉树的遍历方式)
数据结构·算法·leetcode·面试
.生产的驴4 小时前
SpringBoot 接口限流Lua脚本接合Redis 服务熔断 自定义注解 接口保护
java·大数据·数据库·spring boot·redis·后端·lua
Swift社区5 小时前
从表格到序列:Swift 如何优雅地解 LeetCode 251 展开二维向量
开发语言·leetcode·swift
洛可可白6 小时前
Spring Boot中自定义注解的创建与使用
java·spring boot·后端
Alkaid:6 小时前
解决Long类型前端精度丢失和正常传回后端问题
java·前端·javascript·vue.js
唐人街都是苦瓜脸6 小时前
Java RPC 框架是什么
java·开发语言·rpc
魔道不误砍柴功7 小时前
Java性能调优2025:从JVM到Kubernetes的全链路优化策略
java·jvm·kubernetes
多云的夏天7 小时前
C++-FFmpeg-(5)-1-ffmpeg原理-ffmpeg编码接口-AVFrame-AVPacket-最简单demo
java·开发语言
无名之逆7 小时前
[特殊字符] Hyperlane:Rust 高性能 HTTP 服务器库,开启 Web 服务新纪元!
java·服务器·开发语言·前端·网络·http·rust