标签:
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next()
will return the next smallest number in the 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.
Analyse: find the next smallest number in the BST and realize the iteration process. The same as inorder traversal.
Runtime: 28ms.
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class BSTIterator { 11 public: 12 stack<TreeNode* > stk; 13 BSTIterator(TreeNode *root) { 14 while(root){ 15 stk.push(root); 16 root = root->left; 17 } 18 } 19 20 /** @return whether we have a next smallest number */ 21 bool hasNext() { 22 return !stk.empty(); 23 } 24 25 /** @return the next smallest number */ 26 int next() { 27 TreeNode* temp = stk.top(); 28 stk.pop(); 29 int nextMin = temp->val; 30 temp = temp->right; 31 while(temp){ 32 stk.push(temp); 33 temp = temp->left; 34 } 35 return nextMin; 36 } 37 }; 38 39 /** 40 * Your BSTIterator will be called like this: 41 * BSTIterator i = BSTIterator(root); 42 * while (i.hasNext()) cout << i.next(); 43 */
Binary Search Tree Iterator ***
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4699006.html