Implement an iterator over a binary search tree (BST). Your iterator is initialized with the root node of a BST.
Calling would return the next smallest number in the next() BST.
Note: next() hasNext() and should run in average O (1) time and uses O (h) memory, where H is the height of the Tree.
Ideas:
The result is saved to a queue by the middle sequence traversal, hasnext () determines whether the queue is empty, GetNext () returns the queue header element to
1 Public classBstiterator {2 PrivateQueue<integer> Queueofinorder =NewLinkedlist<integer> ();//to save a queue that is traversed by a sequence3 Publicbstiterator (TreeNode root) {4Inorder (root);//Middle Sequence traversal tree, get middle sequence traversal node queue5 }6 7 /** @returnwhether we have a next smallest number*/8 Public BooleanHasnext () {9 if(Queueofinorder.isempty ())Ten return false;//The queue is empty, indicating that the last element has been One return true; A } - - /** @returnThe next smallest number*/ the Public intNext () { -Integer Headofqueue =Queueofinorder.poll (); - - returnHeadofqueue; + } - + /** A * Middle sequence traversal tree at */ - Private voidinorder (TreeNode root) { - if(NULL!=root) { - inorder (root.left); - Queueofinorder.add (root.val); - inorder (root.right); in } - } to}
Binary Search Tree Iterator