Example 1:
Input: [[1,1],2,[1,1]]
Output: 8
Explanation: Four 1’s at depth 1, one 2 at depth 2.
Example 2:
Input: [1,[4,[6]]]
Output: 17
Explanation: One 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 13 + 42 + 6*1 = 17.
先找到depth,再像之前做法一样
class Solution {
int count=0;
public int depthSumInverse(List<NestedInteger> nestedList) {
finddepth(nestedList,0);
return find(nestedList,count);
}
public void finddepth(List<NestedInteger> list,int depth){
for (NestedInteger n : list) {
if(n.isInteger()) {
if(depth+1>count) count=depth+1;
}
else{
finddepth(n.getList(),depth+1);
}
}
}
public int find(List<NestedInteger> list,int weight){
int sum=0;
for (NestedInteger n : list) {
if(n.isInteger()) {
sum+=n.getInteger()*weight;
}
else{
sum+=find(n.getList(),weight-1);
}
}
return sum;
}
}