Created
January 6, 2017 06:12
-
-
Save NodoFox/c73f41ab0500144a171bb512b1825440 to your computer and use it in GitHub Desktop.
Sum of nested list of 'NestedInteger' - Iterative
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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