学习了一种,先算最大的深度,再计算的思路。
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
*
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
* public 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
* public Integer getInteger();
*
* // @return the nested list that this NestedInteger holds, if it holds a nested list
* // Return null if this NestedInteger holds a single integer
* public List<NestedInteger> getList();
* }
*/
public class Solution {
public int depthSumInverse(List<NestedInteger> nestedList) {
int maxDepth = 1;
if (nestedList == null || nestedList.size() == 0) {
return 0;
}
maxDepth = maxDepth(nestedList, maxDepth);
int res = sum(nestedList, maxDepth);
return res;
}
private int sum(List<NestedInteger> nestedList, int depth) {
int sum = 0;
for (NestedInteger nestedInteger: nestedList) {
if (nestedInteger.isInteger()) {
sum = sum + nestedInteger.getInteger() * depth;
} else {
sum = sum + sum(nestedInteger.getList(), depth - 1);
}
}
return sum;
}
private int maxDepth(List<NestedInteger> nestedList, int depth) {
int max = depth;
for (NestedInteger nestedInteger: nestedList) {
if (!nestedInteger.isInteger()) {
max = Math.max(max, maxDepth(nestedInteger.getList(), depth + 1));
}
}
return max;
}
}