Binary Search Tree Iterator
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.
Ideas:
To tell you the truth, this topic at the beginning completely do not understand what I want to do, the return minimum is to find the leftmost node of BST on the line, do not understand what the meaning of the constructor. Internet search to understand, is to be the BST tree sorting, so that the direct output time and space complexity is very low, the constructor is equivalent to a sort of. If the subject is understood, it will be done. Using the characteristics of the BST tree itself, the value of the node is stored in a vector according to the method of the middle sequence traversal, and the elements inside the container are arranged from small to large, so long as the container is not empty, there must be a minimum value. So my solution is a middle sequence traversing a binary tree.
Exercises
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classBstiterator { Public: Vector<int>path; voidInorder (TreeNode *root) { if(Root) {inorder (root-Left ); Path.push_back (Root-val); Inorder (Root-Right ); }} bstiterator (TreeNode*root) {inorder (root); } /** @return Whether we have a next smallest number*/ BOOLHasnext () {if(path.size () = =0) return false; Else return true; } /** @return The next smallest number*/ intNext () {intres = path[0]; Path.erase (Path.begin ()); returnRes; }};/** * Your bstiterator'll be called like this: * bstiterator i = bstiterator (root), * while (I.hasnext ()) cout << ; I.next (); */
View Code
Something:
There are two problems with my approach. The first is that the sequential traversal of the code is simply recursive, relatively time-consuming. The second is that there is actually a better way (method two), which does not need to traverse the entire binary tree in sequence.
[Leetcode] Binary Search Tree Iterator