Strict O(1) time for both hasNext() and next() : a destructive approach

  • 0

    It is still feasible to achieve the time constraints, i.e. a strict O(1) as long as we can change the tree structure. The main idea is to flatten the tree nodes using its right child in order, pretty much like generating an ordered linked list conceptually.

    The following code (still can be improved) fails OJ as expected probably because the destructive change in its structure messes up with the program cleanup. However the output checks out (if you cout the result).

     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
    class BSTIterator {
        BSTIterator(TreeNode *root) {
            // a destructive approach
            // node->right is modified to point to the node with the next larger number.
            // node->left is unchanged
            stack<TreeNode*> s;
            TreeNode *p = nullptr; // the current node already in sequence
            if (root)
            while (!s.empty())
                TreeNode *q;
                while ((q =>left))
                if (p) p->right =;
                while (!((p =>right))
                    if (s.empty()) // only for the last node on the stack
                        p->right =;
                if (p->right)
            if ((it = root))
                while (it->left)
                    it = it->left;
        /** @return whether we have a next smallest number */
        bool hasNext() {
            return it;
        /** @return the next smallest number */
        int next() {
            int val = it->val;
            it = it->right;
            return val;
        TreeNode* it;
     * Your BSTIterator will be called like this:
     * BSTIterator i = BSTIterator(root);
     * while (i.hasNext()) cout <<;

Log in to reply

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