4ms solution, beats 96.5%


  • 1
    J
    public class BSTIterator {
        List<Integer> dp = new ArrayList<>();
        int index=0;
    
        public void inorder(TreeNode root) {
            if (root != null) {
                inorder(root.left);
                dp.add(root.val);
                inorder(root.right);
            }
        }
        
        public BSTIterator(TreeNode root) {
            inorder(root);
        }
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return index < dp.size();
        }
    
        /** @return the next smallest number */
        public int next() {
            return dp.get(index++);
        }
    }

Log in to reply
 

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