Implementing Backward Iterator in BST
Given a Binary search tree, the task is to implement backward iterator on it with the following functions.
- curr(): returns the pointer to current element.
- prev(): iterates to the previous largest element in the Binary Search Tree.
- isEnd(): returns true if there’s no node left to traverse else false.
Iterator traverses the BST in decreasing order. We will implement the iterator using a stack data structure.
Initialisation:
- 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.
Time Complexity: 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.
Time Complexity: O(1) on average of all calls. Can be O(h) for a single call in the worst case.
isEnd()
Returns true if stack “q” is empty else returns false.
Time Complexity: O(1)
Worst Case space complexity for this implementation of iterators is O(h). It should be noticed that
iterator points to the top-most element of the stack.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
node* left;
node* right;
node(int data)
{
this->data = data;
left = NULL;
right = NULL;
}
};
class bstit {
private:
stack<node*> q;
public:
bstit(node* root)
{
node* curr = root;
while (curr != NULL)
q.push(curr), curr = curr->right;
}
node* curr()
{
return q.top();
}
void prev()
{
node* curr = q.top()->left;
q.pop();
while (curr != NULL)
q.push(curr), curr = curr->right;
}
bool isEnd()
{
return !(q.size());
}
};
void iterate(bstit it)
{
while (!it.isEnd())
cout << it.curr()->data << " ", it.prev();
}
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);
bstit it(root);
iterate(it);
return 0;
}
|
Java
import java.util.*;
class node {
int data;
node left;
node right;
node(int data)
{
this.data = data;
left = null;
right = null;
}
}
class bstit
{
Stack<node> q;
public bstit(node root)
{
q = new Stack<>();
node curr = root;
while (curr != null) {
q.add(curr);
curr = curr.right;
}
}
node curr()
{
return q.peek();
}
void prev()
{
node curr = q.peek().left;
q.pop();
while (curr != null) {
q.add(curr);
curr = curr.right;
}
}
boolean isEnd()
{
return (q.size() != 0);
}
void iterate(bstit it)
{
while (it.isEnd()) {
System.out.print(it.curr().data);
System.out.print(" ");
prev();
}
}
}
public class GFG
{
public static void main(String[] args)
{
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);
bstit it = new bstit(root);
it.iterate(it);
}
}
|
Python3
class node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
class bstit:
__stack = []
def __init__(self, root):
curr = root
while (curr is not None):
self.__stack.append(curr)
curr = curr.right
def curr(self):
return self.__stack[-1]
def prev(self):
curr = self.__stack[-1].left
self.__stack.pop()
while (curr != None):
self.__stack.append(curr)
curr = curr.right
def isEnd(self):
return not len((self.__stack))
def iterate(it):
while (not it.isEnd()):
print(it.curr().data,end=" ")
it.prev()
if __name__ == '__main__':
root = node(5)
root.left = node(3)
root.right = node(7)
root.left.left = node(2)
root.left.right = node(4)
root.right.left = node(6)
root.right.right = node(8)
it=bstit(root)
iterate(it)
print()
|
C#
using System;
using System.Collections.Generic;
public class node {
public int data;
public node left;
public node right;
public node(int data) {
this.data = data;
left = null;
right = null;
}
}
public class bstit {
Stack<node> q;
public bstit(node root) {
q = new Stack<node>();
node curr = root;
while (curr != null) {
q.Push(curr);
curr = curr.right;
}
}
public node curr() {
return q.Peek();
}
public void prev() {
node curr = q.Peek().left;
q.Pop();
while (curr != null) {
q.Push(curr);
curr = curr.right;
}
}
public bool isEnd() {
return (q.Count != 0);
}
public void iterate(bstit it) {
while (it.isEnd()) {
Console.Write(it.curr().data);
Console.Write(" ");
prev();
}
}
}
public class GFG {
public static void Main(String[] args) {
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);
bstit it = new bstit(root);
it.iterate(it);
}
}
|
Javascript
<script>
class node
{
constructor(data)
{
this.left = null;
this.right = null;
this.data = data;
}
}
let q = [];
function bstit(root)
{
let curr = root;
while (curr != null)
{
q.push(curr);
curr = curr.right;
}
}
function curr()
{
return q[q.length - 1];
}
function prev()
{
let curr = q[q.length - 1].left;
q.pop();
while (curr != null)
{
q.push(curr);
curr = curr.right;
}
}
function isEnd()
{
return (q.length == 0);
}
function iterate()
{
while (!isEnd())
{
document.write(curr().data + " ");
prev();
}
}
let 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);
bstit(root);
iterate();
</script>
|
Last Updated :
31 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...