Advertisement
imashutosh51

Binary Search Tree Iterator / Implementing Forward Iterator in BST

Aug 5th, 2022
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12.  
  13. /*
  14. Logic:
  15. We will use a stack and push the root node and it's all left elements in stack in constructor.
  16. next function want the next element of inorder so return the top element of stack and push the
  17. right element of top element of stack and push all the left elements
  18.  
  19. hasNext : it return true if there is next element in inorder.
  20. */
  21.  
  22.  
  23. class BSTIterator {
  24.     stack<TreeNode*> st;
  25. public:
  26.     BSTIterator(TreeNode* root) {
  27.        while(root){
  28.            st.push(root);
  29.            root=root->left;
  30.        }
  31.     }
  32.    
  33.     int next() {
  34.         TreeNode *temp=st.top();
  35.         st.pop();
  36.         int res=temp->val;
  37.         if(temp->right){st.push(temp->right);temp=temp->right;
  38.             temp=temp->left;
  39.             while(temp){
  40.                 st.push(temp);
  41.                 temp=temp->left;
  42.             }
  43.         }
  44.         return res;
  45.     }
  46.    
  47.     bool hasNext() {
  48.         if(st.size()) return true;
  49.         return false;
  50.     }
  51. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement