173. Binary Search Tree Iterator

问题描述:

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

 

解题思路:

可以借鉴中序遍历的思路:用栈存储节点,每次栈顶为最小的元素,但是在弹出栈顶后需要更新栈。

 

 

代码:

/**
 * 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) {
        TreeNode* cur = root;
        while(cur){
            stk.push(cur);
            cur = cur->left;
        }
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        if(stk.empty()) return false;
        return true;
    }

    /** @return the next smallest number */
    int next() {
        if(hasNext()){
            TreeNode* cur = stk.top();
            int small = cur->val;
            stk.pop();
            cur = cur->right;
            while(cur){
                stk.push(cur);
                cur = cur->left;
            }
            return small;
        }
        return INT_MAX;
    }
private:
    stack<TreeNode*> stk;
};

/**
 * 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 {
public:
    BSTIterator(TreeNode *root) {
        TreeNode *cur  = root;
        stack<TreeNode*> stk;
        while(cur || !stk.empty()){
            if(cur){
                stk.push(cur);
                cur = cur->left;
            }else{
                cur = stk.top();
                stk.pop();
                val.push_back(cur->val);
                cur = cur->right;
            }
        }
    }

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

    /** @return the next smallest number */
    int next() {
        if(hasNext()){
            int small = val[0];
            val.erase(val.begin());
            return small;
        }
        return INT_MAX;
    }
private:
    vector<int> val;
};

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

 

posted @ 2018-07-12 01:51  妖域大都督  阅读(96)  评论(0编辑  收藏  举报