Skip to content

Latest commit

 

History

History
28 lines (24 loc) · 594 Bytes

86.md

File metadata and controls

28 lines (24 loc) · 594 Bytes

Binary Search Tree Iterator

LeetCode Link

    BSTIterator(TreeNode* root) {
        pushAllLeft(root);
    }
    
    int next() {
        TreeNode* node = stk.top();
        stk.pop();
        if (node->right) {
            pushAllLeft(node->right);
        }
        return node->val;
    }
    
    bool hasNext() {
        return !stk.empty();
    }

    stack<TreeNode*> stk;
    
    void pushAllLeft(TreeNode* node) {
        while (node) {
            stk.push(node);
            node = node->left;
        }
    }