NeetCode #412LC-364MediumTrees
← Back to All Problems#412 · #364 · Nested List Weight Sum II(嵌套列表加权和 II)
📌 Problem Statement & Constraints
This is an interactive problem. You are given a nested list of integers where each element is an integer or a list. Return the sum of every integer multiplied by its weight, where the weight is
maxDepth - depth + 1 (the outermost level has the largest weight). Constraints: the total number of integers is at most 50; the nesting depth is at most 50.💡 Core Algorithmic Approaches
- The weight depends on the maximum depth, which is not known until the whole structure is seen.
- So do a level-by-level BFS, collecting the unweighted sum at each level.
- After the BFS, the number of levels is known, and level
i(0-indexed) gets weightlevels - i. - An alternative single-pass approach accumulates
total + running_sumat each level, which weights outer levels more without knowing the depth in advance.
💻 Benchmark Python3 Implementation
class Solution:
def depthSumInverse(self, nestedList: "List[NestedInteger]") -> int:
# BFS collecting the unweighted sum of each level
levels = []
cur = nestedList
while cur:
nxt = []
s = 0
for item in cur:
if item.isInteger():
s += item.getInteger()
else:
nxt.extend(item.getList())
levels.append(s)
cur = nxt
# level i (0-indexed, outermost first) has weight len(levels) - i
return sum(s * (len(levels) - i) for i, s in enumerate(levels))
# Single-pass variant: each level's sum is added to the total repeatedly
class Solution2:
def depthSumInverse(self, nestedList: "List[NestedInteger]") -> int:
total = 0
running = 0 # sum of all levels seen so far
cur = nestedList
while cur:
nxt = []
for item in cur:
if item.isInteger():
running += item.getInteger()
else:
nxt.extend(item.getList())
total += running # outer levels get counted more often
cur = nxt
return total⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each element is processed once.
💾 Space Complexity
O(w) for the widest level.
⚠️ Interview Pitfalls & Follow-ups
- Assuming the weight is the depth: the weight is
maxDepth - depth + 1, so the outermost level has the largest weight -- the opposite of the standard nested-list weight sum. - Using recursion and computing the depth first, then summing: two passes; the BFS collects everything in one.
- Getting the level order backwards:
levels[0]is the outermost level, which gets the largest weight. - Forgetting that a level may contain only lists: its integer sum is 0, but it still counts as a level for the weighting.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Trees Problems
中文速览与面试要点
嵌套列表加权和 II
(这是一个 交互式问题 )给你一个嵌套列表 nestedList,请返回 nestedList 的 加权和 。与 339 题不同的是,本题的权重是 从下往上 定义的:最底层的整数权重为 1,每向上一层权重加 1。约束:1 ≤ nestedList.length ≤ 50;0 ≤ nestedList[i] 中的整数个数 ≤ 50;0 ≤ nestedList[i] 中的整数 ≤ 100;最大嵌套深度 ≤ 50。
核心要点
- 两遍遍历(标准解) :第一遍求最大深度 maxDepth ,第二遍 DFS 时用 maxDepth − depth + 1 作为权重。
- 为什么权重是 maxDepth − depth + 1 :深度为 1(最上层)的权重最大,深度为 maxDepth(最底层)的权重为 1。
- 一遍遍历的巧妙解法 :用 BFS 逐层累加——维护 unweighted (至今所有元素的和)与 total ;每处理一层, unweighted 累加该层元素和, total 累加 unweighted 。这样上层元素会被重复计入更多次,恰好对应更大的权重。
- 复杂度 :两遍法 O(n) 时间、O(d) 空间(d 为最大深度)。
常见陷阱
- 直接用 depth 作为权重 :那是 339 题(从上往下加权);本题权重需反转。
- 权重公式写成 md − depth :最底层(depth == md)的权重应为 1,因此是 md − depth + 1 。
- 忘记先求最大深度 :无法确定每层的权重。
- BFS 巧妙解法中忘记 unweighted += s :会导致权重计算错误。
参考实现
class Solution:
def depthSumInverse(self, nestedList: list) -> int:
def max_depth(items) -> int:
d = 1
for it in items:
if not it.isInteger():
d = max(d, 1 + max_depth(it.getList()))
return d
md = max_depth(nestedList)
def dfs(items, depth: int) -> int:
s = 0
for it in items:
if it.isInteger():
s += it.getInteger() * (md - depth + 1) # 越靠下权重越小
else:
s += dfs(it.getList(), depth + 1)
return s
return dfs(nestedList, 1)
# 一遍 BFS 的巧妙解法:
# cur, unweighted, total = nestedList, 0, 0
# while cur:
# nxt, s = [], 0
# for it in cur:
# if it.isInteger(): s += it.getInteger()
# else: nxt.extend(it.getList())
# unweighted += s
# total += unweighted # 上层元素被重复累加 -> 权重更大
# cur = nxt
# return total