• LeetCode Binary Search Tree Iterator


    class BSTIterator {
    private:
        TreeNode* current;
        stack<TreeNode*> nodeStack;
    public:
        BSTIterator(TreeNode *root) {
            current = root;
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            if (nodeStack.empty() && current == NULL) {
                return false;
            } else {
                return true;
            }
        }
    
        /** @return the next smallest number */
        int next() {
            while (current != NULL) {
                nodeStack.push(current);
                current = current->left;
            }
            // node current must be null,
            // the last one pushed in the stack must be the smallest one
            
            TreeNode* last = nodeStack.top();
            nodeStack.pop();
            
            // next we will start from its right sub-tree to find the smallest one
            current = last->right;
    
            return last->val;
        }
    };

    好久没写了,最近一直吃翔,看到运行时间分布,Java居然被许多Python超了,看来python大法确实好啊

    第二轮:

    /**
     * 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*> frames;
    public:
        BSTIterator(TreeNode *root) {
            while (root != NULL) {
                frames.push_back(root);
                root = root->left;
            }
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return !frames.empty();
        }
    
        /** @return the next smallest number */
        int next() {
            TreeNode* node = frames.back();
            frames.pop_back();
            if (node->right != NULL) {
                TreeNode* tmp = node->right;
                while (tmp != NULL) {
                    frames.push_back(tmp);
                    tmp = tmp->left;
                }
            }
            return node->val;
        }
    };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */
  • 相关阅读:
    工具包分享-常用工具。by-某某
    渗透常用dos命令,http协议及数据提交方式。 hack 某某
    Hello This Cruel World!
    FFT的一个小技巧
    未完成的模板
    进制转换详细讲解
    CodeForces练习计划
    [SDOI2013]随机数生成器-题解
    动态dp模板
    noip2018游记
  • 原文地址:https://www.cnblogs.com/lailailai/p/4243016.html
Copyright © 2020-2023  润新知