Skip to content

Instantly share code, notes, and snippets.

@NodoFox
Created January 6, 2017 06:12
Show Gist options
  • Save NodoFox/c73f41ab0500144a171bb512b1825440 to your computer and use it in GitHub Desktop.
Save NodoFox/c73f41ab0500144a171bb512b1825440 to your computer and use it in GitHub Desktop.
Sum of nested list of 'NestedInteger' - Iterative
public long sum(List<NestedInteger> list) {
long result = 0;
Queue<NestedInteger> itemQueue = new LinkedList<NestedInteger>();
Queue<Integer> depth = new LinkedList<Integer>();
for(NestedInteger item : list) {
itemQueue.add(item);
depth.add(1);
}
while(!itemQueue.isEmpty()) {
NestedInteger item = itemQueue.poll();
int weight = depth.poll();
if(item.isInteger()) {
result += item.getInteger() * weight;
}else {
for(NestedInteger each : item) {
itemQueue.add(each);
depth.add(weight + 1);
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment