173. Binary Search Tree Iterator

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class BSTIterator {

    Stack<TreeNode> st=new Stack<>();
    
    public BSTIterator(TreeNode root) {
        if(root==null) return;
      while(root!=null)
      {
          
          st.push(root);
          root=root.left;
      }
        
    }
    
    /** @return the next smallest number */
    public int next() {
        
        TreeNode tempNode=st.peek();
        int val=tempNode.val;
        st.pop();
        tempNode=tempNode.right;
        
        while(tempNode!=null)
        {
            st.push(tempNode);
            tempNode=tempNode.left;
            
        }
        
        
        return val;
        
    }
    
    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        
        return !st.isEmpty();
    }
}

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator obj = new BSTIterator(root);
 * int param_1 = obj.next();
 * boolean param_2 = obj.hasNext();
 */

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章