![]() |
VOOZH | about |
Binary Search Trees (BSTs) are data structures, in computer science. They are commonly used for searching, insertion and deletion operations. In situations it becomes necessary to traverse a BST in an order. For example an in order traversal visits nodes in ascending order based on their values. This article explores the creation of a BSTIterator class that facilitates the in order traversal of a search tree.
In this article, we will implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
Notice that by initializing the pointer to a non-existent smallest number, the first call to the next() will return the smallest element in the BST. You may assume that the next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when the next() is called.
Note: Time complexity for next, hasNext - O(1) and Space Complexity - O(N)
To achieve this functionality efficiently we can utilize a stack to keep track of the nodes along the path of the in-order traversal. Here is an explanation of how we can implement the BSTIterator class step by step;
In the constructor we initialize the stack. Populate it with nodes from the leftmost path of the BST. This ensures that initially, the stack contains the elements of the tree.
The pushAllLeft function is a helper function that pushes all nodes from the node to its leftmost child onto the stack.
This method checks whether there are elements to traverse. It returns true if there are still elements remaining in the, in order traversal.
The next() function is responsible, for advancing the pointer to the following element during an in order traversal and returning that element. This is accomplished by removing the node from the stack and subsequently adding all the children of the right subtree of that node back, onto the stack.
To guarantee that all left children of the subtree are included we also utilize the pushAllLeft function in this scenario.
Input: 7
/ \
3 15
/ \
9 20
Output: 3, 7, 9, 15, 20.
Below is the implementation of the BST Iterator:
3 7 9 15 20
Time Complexity: O(N)
Auxiliary Space: O(N)