Concise java solution using stack


  • 2
    Z
    public class BSTIterator {
    
        Stack<TreeNode> s;
        public BSTIterator(TreeNode root) {
            s = new Stack<TreeNode>();
            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 node = result.right;
            while(node!=null)
            {
                s.push(node);
                node = node.left;
            }
            return result.val;
        }
    }
    

  • 0
    V

    Awesome solution.. Thanks!!


Log in to reply
 

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