Topic:
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.
test instructions and analysis: A binary sort tree is given, and the ergodic of the two-fork tree is satisfied: (1) Hasnext () determines whether there is a decimal in the tree except for the current number. (2) Next () returns the decimal number of the tree in addition to the current count. (3) The time Complexity of O (1) and the space Complexity of O (h) are required. Use a stack to save, initially save the value from the root node to the leftmost node, for next, if the stack is non-empty there is hasnext smallest number, for next, the next smallest is the value of the top of the stack (because the left child node of the stack vertex is the current point, The point on the right sub-tree of the stack vertex is certainly larger than the stack vertex, and the point at the top of the stack is removed, and then the upper-left side of the right child node of the point is traversed (that is, the leftmost node that traverses that point to the point).
Code:
/** * Definition for Binary tree * public class TreeNode {* int val, * TreeNode left, * TreeNode right; TreeNode (int x) {val = x;}} */public class Bstiterator {private stack<treenode> Stack; Public bstiterator (TreeNode root) {stack = new stack<> (); TreeNode cur = root; while (cur! = null) {Stack.push (cur); if (cur.left! = null) cur = cur.left; else break; }}/** @return Whether we have a next smallest number */public boolean hasnext () {return!stack.isempty (); }/** @return the next smallest number */public int next () {TreeNode node = Stack.pop (); TreeNode cur = node; Traversal Right Branch if (cur.right! = null) {cur = cur.right; while (cur! = null) {Stack.push (cur); if (cur.left! = null) cur = cur.left; Else Break }} return node.val; }}/** * Your Bstiterator would be a called like this: * bstiterator i = new Bstiterator (root); * while (I.hasnext ()) v[f ()] = I.next (); */
[Leetcode] 173. Binary Search Tree Iterator Java