[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_;
};
posted @ 2017-06-01 16:18  mioopoi  阅读(111)  评论(0编辑  收藏  举报