Java solution


  • 1

    It's actually an InOrder traversal.

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    
    public class BSTIterator {
    
        Stack<TreeNode> stack = new Stack<TreeNode>();
        public BSTIterator(TreeNode root) {
            if(root != null) {
                push(root);
            }
        }
    
        /** @return whether we have a next smallest number */
        public boolean hasNext() {
            return !stack.empty();
        }
    
        /** @return the next smallest number */
        public int next() {
            TreeNode node = stack.pop();
            if(node.right != null){
                push(node.right);
            }
            return node.val;
        }
        
        protected void push(TreeNode node){
            while(node != null) {
                stack.push(node);
                node = node.left;
            }
        }
    }
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = new BSTIterator(root);
     * while (i.hasNext()) v[f()] = i.next();
     */
    
    

  • 0
    B

    Very simple and easy understand! You are my god!!!


Log in to reply
 

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