[LeetCode] Binary Search Tree Iterator | 二叉查找树迭代器

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

难点在于对中间状态的维护。用类似于中序遍历的方法。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
    BSTIterator(TreeNode *root) {
        stk_ = stack<TreeNode*>();
        cur_ = root;
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return ( cur_ || !stk_.empty() );
    }

    /** @return the next smallest number */
    int next() {
        while (cur_) {
            stk_.push(cur_);
            cur_ = cur_ -> left;
        }
        cur_ = stk_.top(); stk_.pop();
        int ret = cur_ -> val;
        cur_ = cur_ -> right;
        return ret;
    }

private:
    stack<TreeNode*> stk_;
    TreeNode* cur_;
};
    原文作者:mioopoi
    原文地址: https://www.cnblogs.com/ilovezyg/p/6929461.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞