给定二进制搜索树,任务是使用以下功能在其上实现向后迭代器。
- curr():返回指向当前元素的指针。
- prev():迭代到二进制搜索树中的前一个最大元素。
- isEnd():如果没有要遍历的节点,则返回true,否则返回false。
迭代器以降序遍历BST。我们将使用堆栈数据结构实现迭代器。
初始化:
- We will create a stack named “q” to store the nodes of BST.
- Create a variable “curr” and initialise it with pointer to root.
- While “curr” is not NULL
- Push “curr” in the stack ‘q’.
- Set curr = curr -> right
curr()
Returns the value at the top of the stack ‘q’.
Note: It might throw segmentation fault if the stack is empty.
时间复杂度: O(1)
prev()
- Declare pointer variable “curr” which points to node.
- Set curr = q.top()->left.
- Pop top most element of stack.
- While “curr” is not NULL
- Push “curr” in the stack ‘q’.
- Set curr = curr -> right.
时间复杂度:平均所有通话为O(1)。在最坏的情况下,单次通话可以为O(h)。
isEnd()
Returns true if stack “q” is empty else returns false.
时间复杂度: O(1)
此迭代器实现的最坏情况下,空间复杂度为O(h)。应该注意的是
迭代器指向堆栈的最顶层元素。
下面是上述方法的实现:
CPP
// C++ implementation of the approach
#include
using namespace std;
// Node of the binary tree
struct node {
int data;
node* left;
node* right;
node(int data)
{
this->data = data;
left = NULL;
right = NULL;
}
};
// Iterator for BST
class bstit {
private:
// Stack to store the nodes
// of BST
stack q;
public:
// Constructor for the class
bstit(node* root)
{
// Initializing stack
node* curr = root;
while (curr != NULL)
q.push(curr), curr = curr->right;
}
// Function to return
// current element iterator
// is pointing to
node* curr()
{
return q.top();
}
// Function to iterate to previous
// element of BST
void prev()
{
node* curr = q.top()->left;
q.pop();
while (curr != NULL)
q.push(curr), curr = curr->right;
}
// Function to check if
// stack is empty
bool isEnd()
{
return !(q.size());
}
};
// Function to test the iterator
void iterate(bstit it)
{
while (!it.isEnd())
cout << it.curr()->data << " ", it.prev();
}
// Driver code
int main()
{
node* root = new node(5);
root->left = new node(3);
root->right = new node(7);
root->left->left = new node(2);
root->left->right = new node(4);
root->right->left = new node(6);
root->right->right = new node(8);
// Iterator to BST
bstit it(root);
// Function call to test the iterator
iterate(it);
return 0;
}
输出:
8 7 6 5 4 3 2
如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。