Describe:
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 ()
and hasnext ()
should run in average O (1) time and uses O (h ) memory, Where h is the height of the tree.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Idea: This problem thought for a long time, know that with the sequence traversal to solve, with a list will traverse the elements stored up a bit to solve, but the complexity of space is not. How to solve the problem, how to terminate the control program has troubled me for a long time. You know, I remember, at most, with O (h) memory, I thought about all the elements that go directly before returning to the beginning of a trip, not exactly the same as the question, bravo!
Code:
/** * Definition for Binary tree * public class TreeNode {* int val, * TreeNode left, * TreeNode right; TreeNode (int x) {val = x;}} */public class Bstiterator {list<integer> List = new arraylist<integer> ();// The value of the storage node Stack<treenode> st = new Stack<treenode> ();//The process of storing the node public bstiterator (TreeNode root) {if (Root! = NULL) St.push (root);} /** @return Whether we have a next smallest number */public Boolean Hasnext () {Boolean flag1 = List.isEmpty (), Flag2 = St. IsEmpty (); if (!FLAG1) return true;if (Flag1 &&!flag2) return Iteratordemo (); return false;} /** @return The next smallest number */public int next () {int num = list.get (0); list.remove (0); return num;} Middle order Traversal Public Boolean Iteratordemo () {TreeNode top = Null;while (!st.empty ()) {top = St.peek (); while (top.left! = null) {St . push (top.left); top = Top.left;} while (top.right = = null) {List.add (top.val); St.pop (); if (!st.empty ()) top = St.peek (); elsebreak;} if (!st.empty ()) {List.add (top.val); sT.pop (); St.push (top.right); break;}} if (List.isEmpty ()) return False;return true;}} /** * Your Bstiterator would be a called like this: * bstiterator i = new Bstiterator (root); * while (I.hasnext ()) v[f ()] = I.next (); */
Results:
Leetcode_173_binary Search Tree Iterator