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.
Design an iterator for a binary search tree. The requirement for next () and Hasnext () is the average O (1) time complexity, the spatial complexity of O (h), and H is the tree height.
1, with the stack to achieve, the stack is stored in the current path of the left child.
/*** Definition for Binary tree * public class TreeNode {* Int. val; * TreeNode left; * TreeNode right; * TreeNode (int x) {val = x;} }*/ Public classBstiterator {Stack<TreeNode>Stack; Publicbstiterator (TreeNode root) {stack=NewStack (); if(Root = =NULL){ return ; } while(Root! =NULL) {Stack.push (root); Root=Root.left; } } /** @returnwhether we have a next smallest number*/ Public BooleanHasnext () {return!Stack.isempty (); } /** @returnThe next smallest number*/ Public intNext () {TreeNode node=Stack.pop (); intAns =Node.val; if(Node.right! =NULL) {node=Node.right; while(Node! =NULL) {Stack.push (node); Node=Node.left; } } returnans; } }/*** Your Bstiterator'll be a called like this: * bstiterator i = new Bstiterator (root), * while (I.hasnext ()) v[f ()] = I.next (); */
2, with the list to achieve. Direct sorting is then stored in the list, and the code is simple and efficient. (refer to discuss).
This method is faster and simpler than the above method, but the space used is O (N), more than the previous one, if the previous test instructions indicates that the design class can only use O (h) space, then this solution is not correct.
Arraydeque<integer>list; Publicbstiterator (TreeNode root) {list=NewArraydeque<integer>(); Inordertraverse (root);}voidinordertraverse (TreeNode root) {if(Root = =NULL) return; Inordertraverse (Root.left); List.addlast (Root.val); Inordertraverse (root.right);}/** @returnwhether we have a next smallest number*/ Public BooleanHasnext () {if(List.isEmpty ())return false; Else return true;}/** @returnThe next smallest number*/ Public intNext () {returnList.removefirst ();}
? Leetcode 173. Binary Search Tree Iterator design iterators (search trees)---------java