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

    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:
        stack<TreeNode*> stk;
    public:
        BSTIterator(TreeNode *root) {
            while(root)
            {
                stk.push(root);
                root=root->left;
            }
        }
    
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return !stk.empty();
        }
    
        /** @return the next smallest number */
        int next() {
            TreeNode*temp=stk.top();
            stk.pop();
            int res=temp->val;
            temp=temp->right;
            while(temp)
            {
                stk.push(temp);
                temp=temp->left;
            }
            return res;
        }
    };
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout << i.next();
     */

      

  • 相关阅读:
    [bzoj 4553][Tjoi2016&Heoi2016]序列
    [bzoj 5143][Ynoi 2018]五彩斑斓的世界
    [bzoj 4939][Ynoi 2016]掉进兔子洞
    luogu_P3674 小清新人渣的本愿
    [bzoj 2809][Apio2012]dispatching
    [bzoj 3110][zjoi 2013]K大数查询
    Entity Framework技巧系列之九
    Entity Framework技巧系列之八
    Entity Framework技巧系列之七
    Entity Framework技巧系列之六
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4758506.html
Copyright © 2011-2022 走看看