Leetcode 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.

题目中要求对二叉搜索树进行线索化,按照题目要求,next()返回下一个最小的元素,那么是需要从小到大排列,即中序遍历。
首先选取数据结构,C++容器中的队列queue满足题目的要求。
1)对二叉搜索树进行中序遍历,将结果存入到队列中。
2)判断has_next,只需要判断队列是否为空。
3)next,即从队列中取出队首的元素,弹出。
代码如下:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
 #include <queue>
 #include <stack>
 using namespace std;

class BSTIterator {
public:
    BSTIterator(TreeNode *root) {
        //对二叉搜索树进行中序遍历,结果存入到队列中
        stack<TreeNode*> node_stack;
        TreeNode* pNode = root;
        while(pNode || !node_stack.empty()){
            if(pNode != NULL){
                node_stack.push(pNode);
                pNode = pNode->left;
            }else{
                pNode = node_stack.top();
                node_stack.pop();
                int_queue.push(pNode->val);
                pNode = pNode->right;
            }
        }


    }


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

    /** @return the next smallest number */
    int next() {
        //队列首元素出列
        if(!int_queue.empty()){
        int result = int_queue.front();
        int_queue.pop();
        return result;
        }else{
            return -1;
        }

    }
private:
    queue<int> int_queue;
};
/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */

猜你喜欢

转载自blog.csdn.net/sunao2002002/article/details/52740615