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.
Problem Solving Ideas:
In fact, according to the order of the sequence traversal, there are two ways to realize:
First, the construction of BST directly under the preprocessing, the construction of a list in accordance with the sequence traversal, each read the elements of the list.
Second, do not pre-processing, according to the idea of sequential traversal using stack dynamic processing
Here we realize the idea of two:
public class Bstiterator {private stack<treenode> stack=new stack<treenode> ();p ublic bstiterator (TreeNode Root) {if (root = null) pushleft (root);} /** @return Whether we have a next smallest number */public Boolean hasnext () {return!stack.isempty ();} /** @return The next smallest number */public int next () {TreeNode top = Stack.peek (); Stack.pop (); if (top.right!=null) PUSHL EFT (top.right); return top.val;} public void Pushleft (TreeNode root) {Stack.push (root); TreeNode roottemp = Root.left;while (roottemp! = null) {Stack.push (roottemp); roottemp = Roottemp.left;}}}
Java for Leetcode 173 Binary Search Tree Iterator