Created
January 6, 2017 05:52
-
-
Save NodoFox/c1fb427b73322e9c8e6a34c018879ff1 to your computer and use it in GitHub Desktop.
Sum of nested list of 'NestedInteger'
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 class Solution { | |
public long sum(List<NestedInteger> list) { | |
return sumRecurse(list, 0); // 0 being the depth | |
} | |
public long sumRecurse(List<NestedInteger> list, int level) { | |
if(list == null || list.size() == 0) { | |
return 0; | |
} | |
long sum = 0; | |
for(NestedInteger element : list) { | |
if(element.isInteger()) { | |
sum = sum + element.getInteger() * level; | |
}else { | |
sum = sum + sumRecurse(element.getList(), level + 1); | |
} | |
} | |
return sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment