跳转至

173.二叉搜索树迭代器 (Medium)*

题目描述*

实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。

调用 next() 将返回二叉搜索树中的下一个最小的数。

提示*

next() 和 hasNext() 操作的时间复杂度是 O(1),并使用 O(h) 内存,其中 h 是树的高度。

你可以假设 next() 调用总是有效的,也就是说,当调用 next() 时,BST 中至少存在一个下一个最小的数。

代码*

可以在初始化时直接生成一个中序遍历序列。或者在每次 next 操作的时候才遍历。

class BSTIterator {
private:
    vector<int> inorder;
    int inorderLength;
    int nextIndex;
public:
    BSTIterator(TreeNode* root) {
        stack<TreeNode*> s;
        TreeNode* cur = root;
        while(cur != nullptr || !s.empty()) {
            while(cur != nullptr) {
                s.push(cur);
                cur = cur->left;
            }
            cur = s.top();
            s.pop();
            inorder.push_back(cur->val);
            cur = cur->right;
        }
        inorderLength = inorder.size();
        nextIndex = 0;
    }

    /** @return the next smallest number */
    int next() {
        if(nextIndex < inorderLength) {
            return inorder[nextIndex++];
        }else {
            return -1;
        }
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return nextIndex < inorderLength;
    }
};
class BSTIterator {
private:
    stack<TreeNode*> innerStack;
    TreeNode *cur;
public:
    BSTIterator(TreeNode* root) {
        cur = root;
    }

    /** @return the next smallest number */
    int next() {
        int res = 0;
        while(cur != nullptr || !innerStack.empty()) {
            while(cur != nullptr) {
                innerStack.push(cur);
                cur = cur->left;
            }
            cur = innerStack.top();
            innerStack.pop();
            res = cur->val;
            cur = cur->right;
            break;
        }
        return res;
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return cur != nullptr || !innerStack.empty();
    }
};

最后更新: July 23, 2022