Share my linkedlist Java solution


  • -1
    M

    This is a solution use linkedlist. Just pre-order the tree and return head of the linkedlist each time.

    public class BSTIterator {
            LinkedList<Integer> node;
            public BSTIterator(TreeNode root) {
                node = new LinkedList<Integer>();
                help(root);
            }
            public void help(TreeNode root){
                if(root==null)return;
                help(root.left);
                node.add(root.val);
                help(root.right);
            }
            
            /** @return whether we have a next smallest number */
            public boolean hasNext() {
                return !node.isEmpty();
            }
        
            /** @return the next smallest number */
            public int next() {
                int next = node.remove();
                return next;
            }
        }

Log in to reply
 

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