LeetCode Binary Search Tree Iterator

class BSTIterator {
private:
    TreeNode* current;
    stack<TreeNode*> nodeStack;
public:
    BSTIterator(TreeNode *root) {
        current = root;
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        if (nodeStack.empty() && current == NULL) {
            return false;
        } else {
            return true;
        }
    }

    /** @return the next smallest number */
    int next() {
        while (current != NULL) {
            nodeStack.push(current);
            current = current->left;
        }
        // node current must be null,
        // the last one pushed in the stack must be the smallest one
        
        TreeNode* last = nodeStack.top();
        nodeStack.pop();
        
        // next we will start from its right sub-tree to find the smallest one
        current = last->right;

        return last->val;
    }
};

好久没写了,最近一直吃翔,看到运行时间分布,Java居然被许多Python超了,看来python大法确实好啊

第二轮:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
private:
    vector<TreeNode*> frames;
public:
    BSTIterator(TreeNode *root) {
        while (root != NULL) {
            frames.push_back(root);
            root = root->left;
        }
    }

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

    /** @return the next smallest number */
    int next() {
        TreeNode* node = frames.back();
        frames.pop_back();
        if (node->right != NULL) {
            TreeNode* tmp = node->right;
            while (tmp != NULL) {
                frames.push_back(tmp);
                tmp = tmp->left;
            }
        }
        return node->val;
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */
原文地址:https://www.cnblogs.com/lailailai/p/4243016.html