My C++ solution using non-recursion inorder traversal


  • 0
    D
    BSTIterator(TreeNode *root) {
        temp = root;
    }
    
    /** @return whether we have a next smallest number */
    bool hasNext() {
        if (temp||!s.empty()) return true;
        else return false;
    }
    
    /** @return the next smallest number */
    int next() {
        while(temp) {
            s.push(temp);
            temp = temp->left;
        }
        res = s.top()->val;
        temp = s.top()->right;
        s.pop();
        return res;
    }
    

    private:

    int res;
    TreeNode *temp;
    stack<TreeNode *> s;

  • 0

    @DjangoBUAA Please do format your code properly using three backquotes ```. B.T.W. there is no need to record the root here.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.