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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Code:
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classBstiterator {Private: Vector<TreeNode*>list; intindex; Public: Bstiterator (TreeNode*root) {bstiterator::treetolist (root, This-list); This->index =0; } Static voidTreetolist (treenode* root, vector<treenode*>&ret) { if(!root)return; Bstiterator::treetolist (Root-Left , ret); Ret.push_back (root); Bstiterator::treetolist (Root-Right , ret); } /** @return Whether we have a next smallest number*/ BOOLHasnext () {returnIndex < This-list.size (); } /** @return The next smallest number*/ intNext () {returnList[index++]->Val; }};/** * Your bstiterator'll be called like this: * bstiterator i = bstiterator (root), * while (I.hasnext ()) cout << ; I.next (); */
Tips
The core of this topic is that the middle sequence traversal converts BST into vectors, which can achieve the requirements of the topic.
"Binary Search Tree Iterator" cpp