您的位置:首页 > 其它

LeetCode Binary Search Tree Iterator

2015-09-12 22:04 225 查看
思路:

在构造函数中就将中序遍历的结果存到队列中,hasNext()与next()依次取队列中的元素。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
private:
    queue<int> minq;
    stack<TreeNode*> s;
    map<TreeNode*, bool> m;
public:
    BSTIterator(TreeNode *root) {
        //inoder traverse
        TreeNode *p = root;
        while(p != NULL || !s.empty()) {
            if(p != NULL) {
                s.push(p);
                p = p->left;
            }else {
                p = s.top();
                s.pop();
                minq.push(p->val);
                p = p->right;
            }
        }
    }

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

    /** @return the next smallest number */
    int next() {
        int front = minq.front();
        minq.pop();
        return front;
    }
};

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


改进:不断构造中序序列而不是一次构造。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
private:
    stack<TreeNode*> s;
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() {
        TreeNode *top = s.top();
        int val = top->val;
        s.pop();
        top = top ->right;
        while(top) {
            s.push(top);
            top = top->left;
        }
        return val;
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: