173. Binary Search Tree Iterator

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next() will return the next smallest number in the BST.
Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.









public class BSTIterator {
    private Stack<TreeNode> stack;

    public BSTIterator(TreeNode root) {
      stack = new Stack<>();
      pushLeft(root);
      
      
        
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
      return !stack.isEmpty();
        
    }

    /** @return the next smallest number */
    public int next() {
      TreeNode node = stack.pop();
      pushLeft(node.right);
      return node.val;
        
    }
    
    private void pushLeft(TreeNode node){
      while(node != null){
        stack.push(node);
        node = node.left;
      }
    }
}

 

posted on 2018-11-06 08:15  猪猪&#128055;  阅读(73)  评论(0)    收藏  举报

导航