LeetCode 341 Flatten Nested List Iterator

Tag: 二叉树 LeetCode Posted on 2022-02-07 23:24:09 Edited on 2022-02-07 23:30:27 Views: 183

概述

https://leetcode.com/problems/flatten-nested-list-iterator/

递归法

class NestedIterator {
public:
    vector<int> list;
    int idx = 0;
    NestedIterator(vector<NestedInteger> &nestedList) {
        helper(nestedList);
    }
    
    void helper(vector<NestedInteger> &nestedList) {
        for (auto e : nestedList) {
            if (e.isInteger()) {
                list.push_back(e.getInteger());
            } else {
                helper(e.getList());
            }
        }
    }
    
    int next() {
        return list[idx++];
    }
    
    bool hasNext() {
        return idx < list.size();
    }
};

迭代法

https://mp.weixin.qq.com/s/uEmD5YVGG5LHQEmJQ2GSfw

大致思想是调用 hasNext 时保证第一个元素为 int,而非列表,如果是列表,就将其拆开放到前面,知道第一个不是列表位置。

未经允许,禁止转载,本文源站链接:https://iamazing.cn/