【Leetcode】364. Nested List Weight Sum II

題目地址:

https://leetcode.com/problems/nested-list-weight-sum-ii/

給定一個NestedInteger類,它要麼是個整數,要麼是一個含NestedInteger對象的列表。現在要求對其所含的所有整數按權重求和,每個節點的權重是其在樹中的高度(即它離最深的葉子的距離)。

思路是BFS。每次把樹上前kk層的“前綴和”加到一個變量裏即可。代碼如下:

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Solution {
    public int depthSumInverse(List<NestedInteger> nestedList) {
    	int res = 0;
    	
    	// sum存前k層的樹上前綴和
    	int sum = 0;
        Queue<NestedInteger> queue = new LinkedList<>();
        for (NestedInteger num : nestedList) {
            queue.offer(num);
        }
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                NestedInteger cur = queue.poll();
                if (cur.isInteger()) {
                    sum += cur.getInteger();
                } else {
                    for (NestedInteger next : cur.getList()) {
                        queue.offer(next);
                    }
                }
            }
            // 累加前綴和
            res += sum;
        }
        
        return res;
    }
}

interface NestedInteger {
    // Constructor initializes an empty nested list.
    // NestedInteger();
    
    // Constructor initializes a single integer.
    // NestedInteger(int value);
    
    // @return true if this NestedInteger holds a single integer, rather than a nested list.
    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
    Integer getInteger();
    
    // Set this NestedInteger to hold a single integer.
    void setInteger(int value);
    
    // Set this NestedInteger to hold a nested list and adds a nested integer to it.
    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
    List<NestedInteger> getList();
}

時空複雜度O(n)O(n)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章