Binary search tree iterator (stack)

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

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
    /*
    *实现一个二叉搜索树迭代器。你将使用二叉搜索树的
    *根节点初始化迭代器。调用 next() 将返回二叉搜索
    *树中的下一个最小的数。
    */
    stack<TreeNode*>st;
    BSTIterator(TreeNode* root) {
        while(root){
            st.push(root);
            root=root->left;
        }
    }
    int next() {
        TreeNode* p=st.top();
        st.pop();
        int ans=p->val;
        p=p->right;
        while(p){
            st.push(p);
            p=p->left;
        }
        return ans;
    }
    bool hasNext() {
        return !st.empty();
    }
};

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator* obj = new BSTIterator(root);
 * int param_1 = obj->next();
 * bool param_2 = obj->hasNext();
 */
Published 152 original articles · praised 2 · visits 6450

Guess you like

Origin blog.csdn.net/weixin_43918473/article/details/104694498