Binary Search Tree Iterator -- leetcode

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.


基本思路:

事实上就是中序遍历的非递实现。


这next smallest意思就是。从小到大逐个返回。 第一次看到,居然理解反了。还以为是从大到小逐个返回。


/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
    BSTIterator(TreeNode *root) {
        while (root) {
            s_.push(root);
            root = root->left;
        }
    }

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

    /** @return the next smallest number */
    int next() {
        auto root = s_.top();
        s_.pop();
        auto ans = root->val;
        root = root->right;
        while (root) {
            s_.push(root);
            root = root->left;
        }
        return ans;
    }

private:
    stack<TreeNode *> s_;
};

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


原文地址:https://www.cnblogs.com/gcczhongduan/p/5265664.html