1. define subproblem
dfsSum will sum up all possible sum for the current level
2. recursive calls
currentSum += sumDfs()
3. stop condition
end of the list return
Code
public int depthSum2(List<NestedInteger> nestedList) {
if (nestedList == null || nestedList.size() == 0) {
return 0;
}
int[] sum = new int[1];
dfsSum(nestedList, sum, 1);
return sum[0];
}
private void dfsSum(List<NestedInteger> nestedList,
int[] sum,
int level) {
for (NestedInteger ele : nestedList) {
if (ele.isInteger()) {
sum[0] += ele.getInteger() * level;
} else {
dfsSum(ele.getList(), sum, level + 1);
}
}
}
BFS Approach
What about BFS? It's easy once we see the nested list as tree. When doing the level order traversal, check if it is list, if so put it back in queue.
Code
public int depthSum(List<NestedInteger> nestedList) {
if (nestedList == null || nestedList.size() == 0) {
return 0;
}
// init queue
Queue<NestedInteger> queue = new LinkedList<>();
for (NestedInteger ele : nestedList) {
queue.offer(ele);
}
int level = 1;
int sum = 0;
// BFS
while (!queue.isEmpty()) {
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
NestedInteger current = queue.poll();
if (current.isInteger()) {
sum += current.getInteger() * level;
} else {
for (NestedInteger ele : current.getList()) {
queue.offer(ele);
}
}
}
level++;
}
// return depth sum
return sum;
}
Now the weight is defined bottom up. The leaf level has weight 1 and so on.
Example
I: [[1,1],2,[1,1]]
O: 8
I: [1,[4,[6]]]
O: 17
DFS Approach
The most obviously approach is doing a two-pass DFS. The first pass is to find the depth. Then the second pass computes the inverse sum with knowledge of the depth.
BFS Approach
Compound sum approach. Layer up as we go.
public int depthSumInverse(List<NestedInteger> nestedList) {
if (nestedList == null || nestedList.size() == 0) {
return 0;
}
// init queue
Queue<NestedInteger> queue = new LinkedList<>();
for (NestedInteger ele : nestedList) {
queue.offer(ele);
}
int totalSum = 0;
int pastLevels = 0;
// BFS
while (!queue.isEmpty()) {
int levelSize = queue.size();
int currentLevel = 0;
for (int i = 0; i < levelSize; i++) {
NestedInteger current = queue.poll();
if (current.isInteger()) {
currentLevel += current.getInteger();
} else {
for (NestedInteger ele : current.getList()) {
queue.offer(ele);
}
}
}
// level++;
pastLevels += currentLevel;
totalSum += pastLevels;
}
// return depth sum
return totalSum;
}