Advertisement
knakul853

Untitled

Jul 24th, 2020
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.65 KB | None | 0 0
  1.  
  2. class BSTIterator {
  3.      stack<TreeNode*>st;
  4. public:
  5.    
  6.     BSTIterator(TreeNode* root) {
  7.        
  8.         mypush(root);
  9.        
  10.     }
  11.      
  12.     /** @return whether we have a next smallest number */
  13.     bool hasNext() {
  14.        
  15.         return !st.empty();
  16.        
  17.     }
  18.  
  19.    
  20.     /** @return the next smallest number */
  21.     int next() {
  22.        
  23.        TreeNode *temp = st.top();
  24.         st.pop();
  25.         mypush(temp->right);
  26.         return temp->val;
  27.        
  28.        
  29.     }
  30.    
  31.    void mypush(TreeNode* node)
  32.     {
  33.         while(node!=NULL)
  34.         {
  35.             st.push(node);
  36.             node=node->left;
  37.         }
  38.     }
  39. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement