LeetCode(437):路径总和 III Path Sum III(Java)

这篇博客介绍了LeetCode中的问题437——路径总和III,作者分享了使用Java解决这个问题的方法,包括基础的递归策略和记忆化回溯的优化技巧。通过哈希表存储已计算的路径值,从根节点开始避免重复计算,寻找目标和的路径。二叉树的最大节点数为1000,节点值范围在-1,000,000到1,000,000之间。" 105224513,8763327,C++双端队列操作详解,"['C++编程', '数据结构', '容器']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2019.10.22 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)

github:https://github.com/ChopinXBP/LeetCode-Babel

二叉树问题一定离不开递归。这题很容易可以想到基础的递归方法:

从每一个结点开始,DFS遍历所有路径

由于存在大量的重复路径,所以也可以考虑将已经计算过的路径值保存在哈希表中,从根节点开始,进行记忆化回溯。

遍历到每一个结点的当前路径长度为curSum,如果之前有路径长度为presum=curSum-target,说明presum至curSum对应结点间必存在一条长度为target的路径。


传送门:路径总和 III

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

给定一个二叉树,它的每个结点都存放着一个整数值。

找出路径和等于给定数值的路径总数。

路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。

示例:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

返回 3。和等于 8 的路径有:
1.  5 -> 3
2.  5 -> 2 -> 1
3.  -3 -> 11


import java.util.HashMap;

/**
 *
 * You are given a binary tree in which each node contains an integer value.
 * Find the number of paths that sum to a given value.
 * The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
 * The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
 * 给定一个二叉树,它的每个结点都存放着一个整数值。
 * 找出路径和等于给定数值的路径总数。
 * 路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
 * 二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。
 *
 */

public class PathSumIII {
   
   
    public class TreeNode 
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值