题目地址:
https://leetcode.com/problems/nested-list-weight-sum-ii/
给定一个NestedInteger类,它要么是个整数,要么是一个含NestedInteger对象的列表。现在要求对其所含的所有整数按权重求和,每个节点的权重是其在树中的高度(即它离最深的叶子的距离)。
思路是BFS。每次把树上前 k k k层的“前缀和”加到一个变量里即可。代码如下:
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Solution {
public int depthSumInverse(List<NestedInteger> nestedList) {
int res = 0;
// sum存前k层的树上前缀和
int sum = 0;
Queue<NestedInteger> queue = new LinkedList<>();
for (NestedInteger num : nestedList) {
queue.offer(num);
}
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
NestedInteger cur = queue.poll();
if (cur.isInteger()) {
sum += cur.getInteger();
} else {
for (NestedInteger next : cur.getList()) {
queue.offer(next);
}
}
}
// 累加前缀和
res += sum;
}
return res;
}
}
interface NestedInteger {
// Constructor initializes an empty nested list.
// NestedInteger();
// Constructor initializes a single integer.
// NestedInteger(int value);
// @return true if this NestedInteger holds a single integer, rather than a nested list.
boolean isInteger();
// @return the single integer that this NestedInteger holds, if it holds a single integer
// Return null if this NestedInteger holds a nested list
Integer getInteger();
// Set this NestedInteger to hold a single integer.
void setInteger(int value);
// Set this NestedInteger to hold a nested list and adds a nested integer to it.
void add(NestedInteger ni);
// @return the nested list that this NestedInteger holds, if it holds a nested list
// Return null if this NestedInteger holds a single integer
List<NestedInteger> getList();
}
时空复杂度 O ( n ) O(n) O(n)。