c# stack solution


  • 0
    N
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    
    public class BSTIterator {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        public BSTIterator(TreeNode root) {
            while(root!=null){
                stack.Push(root);
                root = root.left;
            }
        }
    
        /** @return whether we have a next smallest number */
        public bool HasNext() {
            return stack.Count > 0;
        }
    
        /** @return the next smallest number */
        public int Next() {
            var node = stack.Pop();
            if(node.right!=null){
                var n = node.right;
                while(n!=null){
                    stack.Push(n);
                    n = n.left;
                }
            }
            return node.val;
        }
    }
    
    /**
     * Your BSTIterator will be called like this:
     * BSTIterator i = new BSTIterator(root);
     * while (i.HasNext()) v[f()] = i.Next();
     */
    

Log in to reply
 

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