您的位置:首页 > 其它

Binary Search Tree Iterator -- leetcode

2015-06-26 16:22 302 查看
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();
 */
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: