Java solution taking O(1) space and O(1) time, beating 99% submissions.


  • 3
    F

    A typical Morris traversal approach.

    public class BSTIterator {
        
        private TreeNode current;
        
        public BSTIterator(TreeNode root) {
            current = threadAllNodesOnLeftMostBranch(root);
        }
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return current != null;
        }
    
        /** @return the next smallest number */
        public int next() {
            int result = current.val;
            
            current = current.right;
            // If thread(current) returns false, it means that the left sub tree of current is visited.
            // So there's no need to call threadAllNodesOnLeftMostBranch on current.
            if (current != null && current.left != null && thread(current)) {
                // current is already threaded in the if statement, skip it.
                current = current.left;
                current = threadAllNodesOnLeftMostBranch(current);
            }
            
            return result;
        }
        
        // Thread all nodes on TreeNode root's left-most branch until it reaches the last node on the branch,
        // and return the last node
        private TreeNode threadAllNodesOnLeftMostBranch(TreeNode root) {
            while (root != null && root.left != null) {
                   thread(root);
                   root = root.left;
            }
            
            return root;
        }
        
        // Thread or unthread TreeNode root with its successor
        // Return true if the operation turns out as a threading, and false if unthreading.
        private boolean thread(TreeNode root) {
            TreeNode predecessor  = root.left;
            while (predecessor.right != null && predecessor.right != root) {
                predecessor = predecessor.right;
            }
            if (predecessor.right == null) {
                predecessor.right = root;
                return true;
            } else {
                predecessor.right = null;
                return false;
            }
        }
    }
    

    These solutions also take O(1) space and O(1) time:

    The most voted one has an overhead for threading the tree, it's not as fast as other solutions.

    A good approach which does not break the tree, the implementation not very concise.

    Another approach which breaks the tree structure


  • 0
    S

    per the problem, Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    
    public class BSTIterator {
        
        Iterator<Integer> iterator;
    
        public BSTIterator(TreeNode root) 
        {
            List<Integer> inorder = new ArrayList<>();
            inOrder(root, inorder);
            iterator = inorder.iterator();
        }
        
        private void inOrder(TreeNode node, List<Integer> inOrder)
        {
            if(node != null)
            {
                inOrder(node.left, inOrder);
                inOrder.add(node.val);
                inOrder(node.right, inOrder);
            }
        }
        
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return iterator.hasNext();
        }
    
        /** @return the next smallest number */
        public int next() {
            return iterator.next();
        }
    }
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = new BSTIterator(root);
     * while (i.hasNext()) v[f()] = i.next();
     */

  • 0
    F

    @saivivekh

    Hi, your solution is using not O(h) but O(n) memory since you cached the entire tree by calling inOrder(root, inorder) upon construction. I knew the question asked for a limit of O(h) memory, but isn't O(1) even better? :)


  • 0
    S

    @flacosun i had the dumb 😃 my brain completely ignored the space complexity in the requirement... yes, even though i actually quoted it 😃


Log in to reply
 

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