75-days-dsa-challenge

Ninja technique🥷 to ACE DSA Interviews.

View the Project on GitHub

173. Binary Search Tree Iterator

Solution

Code


class BSTIterator {
private:
    stack<TreeNode*> st;

public:
    BSTIterator(TreeNode* root)
    {
        st = stack<TreeNode*>();
        addAllLeft(root);
    }

    int next()
    {
        TreeNode* topValue = st.top();
        st.pop();
        addAllLeft(topValue->right);
        return topValue->val;
    }

    bool hasNext()
    {
        return !st.empty();
    }

    void addAllLeft(TreeNode* root)
    {
        while (root != nullptr) {
            st.push(root);
            root = root->left;
        }
    }
};