-
BingoPython:
class BSTIterator: # @param root, a binary search tree's root node def __init__(self, root): self.stack = [] self.pushLeft(root) # @return a boolean, whether we have a next smallest number def hasNext(self): return self.stack # @return an integer, the next smallest number def next(self): top = self.stack.pop() self.pushLeft(top.right) return top.val def pushLeft(self, node): while node: self.stack.append(node) node = node.left
-
BingoC++:
class BSTIterator { public: BSTIterator(TreeNode *root) { while (root) { s.push(root); root = root->left; } } /** @return whether we have a next smallest number */ bool hasNext() { return !s.empty(); } /** @return the next smallest number */ int next() { TreeNode *n = s.top(); s.pop(); int res = n->val; if (n->right) { n = n->right; while (n) { s.push(n); n = n->left; } } return res; } private: stack<TreeNode*> s; };
-
BingoJava:
public class BSTIterator { private Stack<TreeNode> stack = new Stack<TreeNode>(); public BSTIterator(TreeNode root) { pushAll(root); } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode tmpNode = stack.pop(); pushAll(tmpNode.right); return tmpNode.val; } private void pushAll(TreeNode node) { for (; node != null; stack.push(node), node = node.left); } }
-