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.
===================================================================
題目鏈接:https://leetcode.com/problems/binary-search-tree-iterator/
題目大意:使用 O(1) 的時間複雜度和 O(h) 的空間複雜度實現二叉搜索樹的判斷是否有下一個值hasNext()和輸出下一個值next()的操作。
思路:模擬二叉搜索樹的非遞歸版中序遍歷。
參考代碼:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
node.clear() ;
cur = root ;
}
/** @return whether we have a next smallest number */
bool hasNext() {
if ( cur || ! node.empty() )
{
while ( cur )
{
node.push_back ( cur ) ;
cur = cur -> left ;
}
return true ;
}
return false ;
}
/** @return the next smallest number */
int next() {
cur = node.back() ;
node.pop_back() ;
int ans = cur -> val ;
cur = cur -> right ;
return ans ;
}
private :
vector <TreeNode*> node ;
TreeNode* cur ;
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/