Description:
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.
題意:
給一個二叉搜索樹的根節(jié)點(diǎn),實(shí)現(xiàn)從小到大的迭代,每次調(diào)用函數(shù)next()
都輸出當(dāng)前最小的節(jié)點(diǎn)的值,hasNext()
則用于檢測是否還有剩下沒輸出的節(jié)點(diǎn)。
Link:
https://leetcode.com/problems/binary-search-tree-iterator/description/
解題方法:
對于二叉搜索樹,中序遍歷是最直接的方法,但是這道題要求O(h) space,也就是說差不多每層只能儲存1個節(jié)點(diǎn)。
所以在棧里面,從根節(jié)點(diǎn)開始,只壓棧本身和左孩子。
當(dāng)每次調(diào)用next()
的時候,彈出一個結(jié)點(diǎn),如果這個節(jié)點(diǎn)有右孩子,則把右孩子當(dāng)成root再進(jìn)行一次構(gòu)造函數(shù)。
Time Complexity:
構(gòu)造函數(shù)O(h) time O(h) space
hasNext()
O(1) time
next()
O(1) time
完整代碼:
class BSTIterator
{
public:
BSTIterator(TreeNode *root)
{
while(root)
{
S.push(root);
root = root->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext()
{
return !S.empty();
}
/** @return the next smallest number */
int next()
{
TreeNode* curr = S.top();
S.pop();
if(curr->right)
{
TreeNode* rightChild = curr->right;
while(rightChild)
{
S.push(rightChild);
rightChild = rightChild->left;
}
}
return curr->val;
}
private:
stack<TreeNode*> S;
};