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.
传统的中序遍历采用递归的方式就可以顺序读取二叉搜索树中的内容,但是由于程序栈很很深具有较大的开销,因此采用一个栈来记录之前的路径,采用迭代的方式完成遍历更加高效。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
//采用中序遍历可以按照从小到大遍历BST,这里是实现中序遍历器的含义,定义一个stack记录之前的位置
stack<TreeNode*> s;
TreeNode* current = NULL;//记录当前节点左子树的指针,对于当前节点的下一个最小节点可能是current的最左子树,如果current为空表示
//上一次遍历的节点没有右子树,就从栈中取
BSTIterator(TreeNode *root) {
current = root;
/*while(node->left != NULL)
{
s.push(node);
node = node->left;
}
current = node;*/
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !(current==NULL && s.empty());
}
/** @return the next smallest number */
int next() {
TreeNode *temp = NULL;
if(current == NULL)
{
if(!s.empty())
{
temp = s.top();
s.pop();
current = temp->right;
}
}else
{
while(current->left != NULL)
{
s.push(current);
current = current->left;
}
temp = current;
current = current->right;
}
return temp->val;
}
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/