My Java Solution using ArrayList


  • 0
    E
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    
    public class BSTIterator {
        public static ArrayList<Integer>list;
        public static int len;
        public BSTIterator(TreeNode root) {
            list=new ArrayList<Integer>();
            inOrder(root,list);
            len=0;
        }
        public void inOrder(TreeNode root, ArrayList<Integer>list){
            if(root==null){
                return;
            }
            inOrder(root.left,list);
            list.add(root.val);
            inOrder(root.right,list);
        }
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            if(len<list.size()){
                return true;
            }
            return false;
        }
    
        /** @return the next smallest number */
        public int next() {
            return list.get(len++);
        }
    }
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = new BSTIterator(root);
     * while (i.hasNext()) v[f()] = i.next();
     */
    

Log in to reply
 

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