二叉查找树迭代器

来源:互联网 发布:淘宝采集软件收费吗 编辑:程序博客网 时间:2024/05/21 19:49

设计实现一个带有下列属性的二叉查找树的迭代器:

  • 元素按照递增的顺序被访问(比如中序遍历)

  • next()hasNext()的询问操作要求均摊时间复杂度是O(1)



/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 * Example of iterate a tree:
 * BSTIterator iterator = BSTIterator(root);
 * while (iterator.hasNext()) {
 *    TreeNode * node = iterator.next();
 *    do something for node
 */




class BSTIterator {
public:
    /*
    * @param root: The root of binary tree.
    */
    BSTIterator(TreeNode * root) {
        // push all left nodes to stack
        while (root != NULL) {
            stack_.push(root);
            root = root->left;
        }
    }


    /*
     * @return: True if there has next node, or false
     */
    bool hasNext() {
        // stack isn't null
        return !stack_.empty();
    }


    /*
     * @return: return next node
     */
    TreeNode * next() {
        // write your code here
        TreeNode* tn = stack_.top();
        stack_.pop();
        // next is right child if not null
        TreeNode* root = tn->right;
        while (root != NULL) {
            stack_.push(root);
            root = root->left;
        }
        return tn;
    }


 private:
    // stack to keep minimal nodes
    stack<TreeNode*> stack_;
};

原创粉丝点击