C# Solution (Beats 85%) O(1) runtime and O(h) space


  • 0
    K

    public class BSTIterator {

    private Stack<TreeNode> stack;
    
    public BSTIterator(TreeNode root) 
    {
        stack = new Stack<TreeNode>();
        TreeNode currNode = root;
        while(currNode != null)
        {
            stack.Push(currNode);
            currNode = currNode.left;
        }
        
    }
    
    /** @return whether we have a next smallest number */
    public bool HasNext() 
    {
        return stack.Count > 0;
    }
    
    /** @return the next smallest number */
    public int Next() 
    {
        TreeNode node = stack.Pop();
        int val = node.val;
        
        node = node.right;
        while(node != null)
        {
            stack.Push(node);
            node = node.left;
        }
        
        
        return val;
    }
    

    }


Log in to reply
 

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