C# with stack


  • 0
    H
    public class BSTIterator {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        
        public BSTIterator(TreeNode root) {
            TraverseLeft(root);
        }
    
        /** @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();
            TraverseLeft(node.right);
            
            return node.val;
        }
        
        public void TraverseLeft(TreeNode root) {
            while(root != null) { 
                stack.Push(root); 
                root = root.left; 
            }
        }
    }
    

Log in to reply
 

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