BST Iterator Problem Statement

You are tasked with implementing a class BSTIterator, which is designed to traverse a Binary Search Tree (BST) in the inorder manner. The class must support the following operations:

  1. BSTIterator(Node root) - A constructor that initializes the iterator with the root of the BST.
  2. next() - Returns the next element in the inorder traversal.
  3. hasNext() - Returns true if there are more elements to traverse, false otherwise.
  4. prev() - Returns the previous element from the current inorder traversal point.
  5. hasPrev() - Returns true if there is a previous element to access, false otherwise.

Input:

The input starts with an integer 'T', representing the number of test cases. Each test case consists of a single line containing the tree's elements in level-order traversal format, with tree node values separated by spaces. Use -1 to represent null nodes.

Output:

For each test case, output a single line containing space-separated integers, which represents the inorder traversal of the binary search tree.

Example:

Input:
4
2 6
1 3 5 7
-1 -1 -1 -1 -1 -1

Output:
1 2 3 4 5 6 7

Constraints:

  • 1 <= T <= 10
  • 1 <= N <= 10^4
  • 1 <= A[i] <= 10^9

Note:

While reading the tree input, the first not null node of a level becomes the parent for its left and right children in the next level. Continue this until all nodes at the last level are processed. You do not need to handle output printing as it is already managed.

Be the first one to answer
Add answer anonymously...
Amazon Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter