Binary Search Tree Iterator in C++

C++Server Side ProgrammingProgramming

Suppose we want to make one iterator for binary tree. There will be two methods. The next() method to return the next element, and hasNext() method to return Boolean value, that will indicate that the next element is present or not. So if the tree is like −


And the sequence of function calls are [next(), next(), hasNext(), next(), hasNext(),next(), hasNext(),next(), hasNext()]. The output will be [3,7,true,9,true,15,true,20,false]

To solve this, we will follow these steps −

  • There are two methods next and hasNext,

  • The next() method will be like −

  • if right of curr is not null, then push inorder successor from the right of node

  • The hasNext() method will be like −

  • return true, when stack is not empty, otherwise false.

Let us see the following implementation to get better understanding −

Example

class BSTIterator {
   public:
   stack <TreeNode*> st;
   void fillStack(TreeNode* node){
      while(node){
         st.push(node);
         node=node->left;
      }
   }
   BSTIterator(TreeNode* root) {
      fillStack(root);
   }
   /** @return the next smallest number */
   int next() {
      TreeNode* curr = st.top();
      st.pop();
      if(curr->right){
         fillStack(curr->right);
      }
      return curr->val;
   }
   /** @return whether we have a next smallest number */
   bool hasNext() {
      return !st.empty();
   }
};

Input

["BSTIterator","next","next","hasNext","next","hasNext","next","hasNext","next","hasNext"]
[[[7,3,15,null,null,9,20]],[null],[null],[null],[null],[null],[null],[null],[null],[null]]

Output

[null,3,7,true,9,true,15,true,20,false]
raja
Published on 05-Feb-2020 09:45:10
Advertisements