173. Binary Search Tree Iterator

来源:互联网 发布:淘宝云客服工资怎么算 编辑:程序博客网 时间:2024/06/13 21:36

mplement 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.

一开始没看条件,直接写了如下解法。

class BSTIterator {public:    queue<int> minq;    BSTIterator(TreeNode *root) {        stack<TreeNode*> st;        while (root != NULL || !st.empty()) {            if (root != NULL) {                st.push(root);                root = root->left;            }            else {                root = st.top();                minq.push(root->val);                root = root->right;            }        }    }    /** @return whether we have a next smallest number */    bool hasNext() {        return !minq.empty();    }    /** @return the next smallest number */    int next() {        int minval = minq.front();        minq.pop();        return minval;    }};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */

时间上是绝对的O(1),空间上确实O(N).

不知道如果做到时间O(1)还能空间O(logN).

给出时间空间都是O(logN)解法。

class BSTIterator {public:    stack<TreeNode*> st;    BSTIterator(TreeNode *root) {        pushleft(root);    }    void pushleft(TreeNode *root) {        while (root != NULL) {            st.push(root);            root = root->left;        }    }    /** @return whether we have a next smallest number */    bool hasNext() {        return !st.empty();    }    /** @return the next smallest number */    int next() {        TreeNode* temp = st.top();        st.pop();        pushleft(temp->right);        return temp->val;    }};
原创粉丝点击