leetcode 173. 二叉搜索树迭代器

https://leetcode-cn.com/problems/binary-search-tree-iterator/

两个栈

class BSTIterator {
public:
    BSTIterator(TreeNode* root) {
        inorder(root);
        dump_stack();
    }
    
    /** @return the next smallest number */
    int next() {
        int ret = s2.top();
        s2.pop();
        return ret;
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !s2.empty();
    }
    
    void inorder(TreeNode* root)
    {
        if (root == NULL) return;
        inorder(root->left);
        s1.push(root->val);
        inorder(root->right);
    }
    
    void dump_stack()
    {
        while(!s1.empty())
        {
            s2.push(s1.top());
            s1.pop();
        }
    }
    
    stack s1;
    stack s2;
};

一个栈

class BSTIterator {
public:
    BSTIterator(TreeNode* root) {
        cur = root;
        while(cur != NULL)
        {
            s.push(cur);
            cur = cur->left;
        }
    }
    
    /** @return the next smallest number */
    int next() {
        while(cur != NULL)
        {
            s.push(cur);
            cur = cur->left;
        }        
        cur = s.top();
        s.pop();
        int ret = cur->val;
        cur = cur->right;
        return ret;
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !s.empty() || cur != NULL;
    }  

    TreeNode* cur;
    stack s;
};

 

你可能感兴趣的:(面试算法,leetcode)