Skip to content

Commit 4b1a6e6

Browse files
authored
Create 339. Nested List Weight Sum.java
1 parent 2e35911 commit 4b1a6e6

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

339. Nested List Weight Sum.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* // This is the interface that allows for creating nested lists.
3+
* // You should not implement it, or speculate about its implementation
4+
* public interface NestedInteger {
5+
*
6+
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
7+
* public boolean isInteger();
8+
*
9+
* // @return the single integer that this NestedInteger holds, if it holds a single integer
10+
* // Return null if this NestedInteger holds a nested list
11+
* public Integer getInteger();
12+
*
13+
* // @return the nested list that this NestedInteger holds, if it holds a nested list
14+
* // Return null if this NestedInteger holds a single integer
15+
* public List<NestedInteger> getList();
16+
* }
17+
*/
18+
public class Solution {
19+
public int helper(List<NestedInteger> nl, int depth) {
20+
int sum = 0;
21+
for (int i = 0; i < nl.size(); i++) {
22+
if (nl.get(i).isInteger()) {
23+
sum += nl.get(i).getInteger() * depth;
24+
} else {
25+
sum += helper(nl.get(i).getList(), depth+1);
26+
}
27+
}
28+
return sum;
29+
}
30+
31+
public int depthSum(List<NestedInteger> nestedList) {
32+
return helper(nestedList, 1);
33+
}
34+
}

0 commit comments

Comments
 (0)