zoukankan      html  css  js  c++  java
  • 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.

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class BSTIterator {
    private:
        stack<TreeNode *> sta;
    public:
    void leftOrder(TreeNode *root)
    {
        if(root==NULL)return;
        TreeNode *tmp=root;
        while(tmp)
        {
            sta.push(tmp);
            if(tmp->left)
            {
                tmp=tmp->left;
            }
            else break;
        }
        return;
    }
        BSTIterator(TreeNode *root) {
          leftOrder(root); 
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
           return !sta.empty(); 
        }
    
        /** @return the next smallest number */
        int next() {
            TreeNode *top=sta.top();
            sta.pop();
            if(top->right)leftOrder(top->right);
            return top->val;
        }
    };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */
  • 相关阅读:
    PLSQL设置中文
    新建oracle实例
    eclipse中导入项目后中文成乱码解决办法
    安装oracle
    配置java环境变量
    学习springMVC实例1——配置和跳转到HelloWorld
    突破变态限制快捷方式提权法
    对象的内存布局
    XMl转Map-map调用公共模板
    对象的创建
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4280657.html
Copyright © 2011-2022 走看看