【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)

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 创作都市 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读