【Binary Search Tree Iterator 】cpp

题目:

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 {
private:
    vector<TreeNode*> list;
    int index;
public:
    BSTIterator(TreeNode *root) {
        BSTIterator::treeToList(root, this->list);
        this->index = 0;
    }

    static void treeToList(TreeNode* root, vector<TreeNode*>& ret)
    {
        if ( !root ) return;
        BSTIterator::treeToList(root->left, ret);
        ret.push_back(root);
        BSTIterator::treeToList(root->right, ret);
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return index < this->list.size();
    }

    /** @return the next smallest number */
    int next() {
        return list[index++]->val;
    }
};

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

tips:

这个题目的核心就是在于中序遍历 把BST转化成vector,这样可以实现题目的要求。

posted on 2015-07-14 19:25  承续缘  阅读(201)  评论(0编辑  收藏  举报

导航