173. Binary Search Tree Iterator

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/BigFatSheep/article/details/79969009

问题描述

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
题目链接:


思路分析

实现一个二叉搜索树的迭代器,能够在O(1)的时间内返回下一个最小的数,O(h)的时间内判断是否有下一个数。

因为二叉搜索树的性质,最小的数肯定是在最左边,然后是它的根结点,再是它的右子树。为了实现回滚,使用一个栈来保存树结点,将左子树先入栈,然后才是右子树。

代码

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
    stack<TreeNode *> stk;
public:
    BSTIterator(TreeNode *root) {
        pushAll(root);
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !stk.empty();
    }

    /** @return the next smallest number */
    int next() {
        TreeNode *temp = stk.top();
        stk.pop();
        pushAll(temp->right);
        return temp->val;
    }
private:
    void pushAll(TreeNode * node){
        while(node){
            stk.push(node);
            node = node->left;
        }
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */

时间复杂度:O(1)
空间复杂度:O(n)


反思

阅读更多

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