leetcode
leetcode 551 ~ 600
路径总和 IV

路径总和 IV

难度:

标签:

题目描述

代码结果

运行时间: 22 ms, 内存: 0.0 MB


/*
 * Problem: Path Sum IV (LeetCode 666)
 * 
 * The task is to find the total sum of all the path sums from the root to the leaf nodes.
 * This solution uses Java Streams to create the tree and calculate the sum.
 */
 
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
 
public class PathSumIVStream {
    // Map to store the tree nodes with their depths and positions
    private Map<Integer, Integer> tree;
    // Variable to store the total path sum
    private int totalSum = 0;
 
    public int pathSum(int[] nums) {
        // Construct the tree map using streams
        tree = IntStream.of(nums).boxed().collect(Collectors.toMap(
            num -> (num / 100) * 10 + (num / 10) % 10,
            num -> num % 10
        ));
        // Start DFS traversal from the root node (depth 1, position 1)
        dfs(1, 1, 0);
        return totalSum;
    }
 
    private void dfs(int depth, int position, int currentSum) {
        // Key for the current node
        int key = depth * 10 + position;
        // If the node doesn't exist, return
        if (!tree.containsKey(key)) return;
 
        // Update the current path sum
        currentSum += tree.get(key);
 
        // Calculate the keys for left and right children
        int leftKey = (depth + 1) * 10 + (position * 2 - 1);
        int rightKey = (depth + 1) * 10 + (position * 2);
 
        // If the node is a leaf, add the current path sum to the total sum
        if (!tree.containsKey(leftKey) && !tree.containsKey(rightKey)) {
            totalSum += currentSum;
        } else {
            // Recursively visit left and right children
            dfs(depth + 1, position * 2 - 1, currentSum);
            dfs(depth + 1, position * 2, currentSum);
        }
    }
 
    public static void main(String[] args) {
        PathSumIVStream solution = new PathSumIVStream();
        int[] nums = {113, 215, 221};
        System.out.println(solution.pathSum(nums)); // Output should be the total path sum
    }
}

解释

方法:

该题解的思路是将给定的数字数组转化为一个字典,用于表示二叉树。字典的键为节点编号,值为节点值。然后使用深度优先搜索遍历二叉树,计算从根节点到每个叶子节点的路径和,最后返回所有路径和的总和。在遍历过程中,通过节点编号计算左右子节点的编号,判断子节点是否存在,递归计算路径和。

时间复杂度:

O(n)

空间复杂度:

O(n)

代码细节讲解

🦆
为什么在构建二叉树字典时,使用`num // 10`作为键和`num % 10`作为值,它们分别代表什么含义?
在构建二叉树字典时,`num // 10`作为键,`num % 10`作为值的做法是为了从给定的数字中分离出节点的位置信息和节点的值。在此题中,每个数字由三位组成,其中最左边的一位代表节点的层次(depth),中间的一位代表该层次中的位置(position),最右边的一位代表节点的值。使用`num // 10`可以去掉最后一位,从而得到由层次和位置组成的两位数,这两位数作为键,可以唯一标识一个节点的位置。而`num % 10`则直接获取该节点的值。
🦆
在计算左右子节点的编号时,公式`(depth + 1) * 10 + pos * 2 - 1`和`(depth + 1) * 10 + pos * 2`是如何得出的?这种编号方法有什么特别的含义吗?
该公式是基于二叉树的层次和位置编号规则来计算子节点的编号。在二叉树中,如果一个节点位于第`depth`层,位置为`pos`,那么它的左子节点将位于第`depth+1`层,位置为`2*pos-1`;右子节点位于同一层,位置为`2*pos`。因此,公式`(depth + 1) * 10 + pos * 2 - 1`用于计算左子节点的编号,`(depth + 1) * 10 + pos * 2`用于计算右子节点的编号。这种编号方法便于从父节点直接计算出子节点的位置编号,保持树结构的清晰和操作的简便性。
🦆
如果左子节点或右子节点不存在于字典中,我们如何确保节点确实是叶子节点而不是因为输入数据的缺失?
在本题的上下文中,我们假设给定的输入数据是完整的,即不存在数据缺失的情况。因此,如果某个节点的左子节点或右子节点的编号不在字典中,我们可以认为这是因为该节点是叶子节点。在实际应用中,若有可能存在数据不完整的情况,那么这种方法可能需要调整,以确保正确判断叶子节点。
🦆
递归函数`traverse`中,为什么要将`preSum + binaryTree[cur]`作为参数传递给子递归调用?这样做有什么优势?
在递归函数`traverse`中,`preSum + binaryTree[cur]`作为参数传递给子递归调用主要是为了在递归过程中累积当前路径上的节点值之和。这样做的优势是可以在每个递归调用中直接得到从根节点到当前节点的路径和,无需在每次返回时重新计算或存储路径上的节点值。这种方法提高了效率,减少了重复计算,并且使代码更加简洁和易于理解。

相关问题

路径总和

给你二叉树的根节点 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

路径总和 II

给你二叉树的根节点 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

二叉树中的最大路径和

二叉树中的 路径 被定义为一条节点序列,序列中每对相邻节点之间都存在一条边。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。

路径和 是路径中各节点值的总和。

给你一个二叉树的根节点 root ,返回其 最大路径和

 

示例 1:

输入:root = [1,2,3]
输出:6
解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6

示例 2:

输入:root = [-10,9,20,null,null,15,7]
输出:42
解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42

 

提示:

  • 树中节点数目范围是 [1, 3 * 104]
  • -1000 <= Node.val <= 1000

路径总和 III

给定一个二叉树的根节点 root ,和一个整数 targetSum ,求该二叉树里节点值之和等于 targetSum路径 的数目。

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

 

示例 1:

输入:root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
输出:3
解释:和等于 8 的路径有 3 条,如图所示。

示例 2:

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

 

提示:

  • 二叉树的节点个数的范围是 [0,1000]
  • -109 <= Node.val <= 109 
  • -1000 <= targetSum <= 1000