Binary Search Tree Iterator
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
题意差不多就是将BST按中序非递归输出。当然stack。
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*> s; 13 BSTIterator(TreeNode *root) { 14 while(root) 15 { 16 s.push(root); 17 root = root->left; 18 } 19 } 20 21 /** @return whether we have a next smallest number */ 22 bool hasNext() { 23 if(s.empty()) return false; 24 else return true; 25 } 26 27 /** @return the next smallest number */ 28 int next() { 29 TreeNode* tmp = s.top(); 30 int result = tmp->val; 31 s.pop(); 32 tmp = tmp->right; 33 while(tmp) 34 { 35 s.push(tmp); 36 tmp = tmp->left; 37 } 38 return result; 39 } 40 }; 41 42 /** 43 * Your BSTIterator will be called like this: 44 * BSTIterator i = BSTIterator(root); 45 * while (i.hasNext()) cout << i.next(); 46 */