Title: (Tree Stack)
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.
Exercises
Tree's problem is easily linked to stack, the problem is to maintain a stack on it.
With Pushleft ()
/** Definition for binary tree * public class TreeNode {* Int. val; * TreeNode left; * TreeNode right; * TreeNode (int x) {val = x;} }*/ Public classBstiterator {//TreeNode Root;stack<treenode> stack =NewStack<treenode>(); Publicbstiterator (TreeNode root) {pushleft (root); } /** @return Whether we have a next smallest number*/ PublicBoolean hasnext () {return!Stack.isempty (); } /** @return The next smallest number*/ Public intNext () {TreeNode small=Stack.pop (); Pushleft (Small.right); returnSmall.val; } Public voidpushleft (TreeNode root) { while(root!=NULL) {Stack.push (root); Root=Root.left; } }}/** * Your bstiterator'll be called like this: * bstiterator i = new Bstiterator (root), * while (I.hasnext ()) v[f ()] = I.next (); */
Constantly push the root.left to the stack, and if that node had right child at the time of the backtracking, then more of that right child would be pushleft ().
[Leetcode] Binary Search Tree