其实本题并不难,没有解出主要是题干没有写清楚,不知道是level还是height,
后来搞明白[[b], a, [c, d]],在这个例子中,b是在level 2的,而不是level 1,即便他是leaf node。
这样就是一个很简单的用BFS的问题。
代码如下:
/*** // This is the interface that allows for creating nested lists.* // You should not implement it, or speculate about its implementation* public interface NestedInteger {* // Constructor initializes an empty nested list.* public NestedInteger();** // Constructor initializes a single integer.* public NestedInteger(int value);** // @return true if this NestedInteger holds a single integer, rather than a nested list.* public boolean isInteger();** // @return the single integer that this NestedInteger holds, if it holds a single integer* // Return null if this NestedInteger holds a nested list* public Integer getInteger();** // Set this NestedInteger to hold a single integer.* public void setInteger(int value);** // Set this NestedInteger to hold a nested list and adds a nested integer to it.* public void add(NestedInteger ni);** // @return the nested list that this NestedInteger holds, if it holds a nested list* // Return null if this NestedInteger holds a single integer* public List<NestedInteger> getList();* }*/class Solution {public int depthSumInverse(List<NestedInteger> nestedList) {if (nestedList == null || nestedList.isEmpty()) {return 0;}Queue<NestedInteger> queue = new LinkedList<>();queue.addAll(nestedList);int preSum = 0;int sum = 0;while (!queue.isEmpty()) {int levelSum = 0;int sz = queue.size();for (int i = 0; i < sz; ++i) {NestedInteger ni = queue.poll();if (ni.isInteger()) {levelSum += ni.getInteger();}else {queue.addAll(ni.getList());}}preSum += levelSum;sum += preSum;}return sum;}}
