Simple Java solution!


  • 0
    A
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    
    public class BSTIterator {
        Stack<TreeNode> s = new Stack<TreeNode>();
        public BSTIterator(TreeNode root) {
            while (root != null){
                s.push (root);
                root = root.left;
            }
        }
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return !s.isEmpty();
        }
    
        /** @return the next smallest number */
        public int next() {
            TreeNode result = s.pop();
            TreeNode temp = result.right;
            while (temp != null){
                s.push(temp);
                temp = temp.left;
            }
            return result.val;
        }
    }
    
    /**
     * 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.