Skip to content

Instantly share code, notes, and snippets.

@z0marlin
Created November 3, 2018 16:13
Show Gist options
  • Save z0marlin/6a22a1ce2daefb5ef2e033f15248aff7 to your computer and use it in GitHub Desktop.
Save z0marlin/6a22a1ce2daefb5ef2e033f15248aff7 to your computer and use it in GitHub Desktop.
WEC Codebuddy week5 3rd sem solution
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
stack<TreeNode*> s;
BSTIterator::BSTIterator(TreeNode *root) {
TreeNode* temp = root;
while (temp!=NULL){
s.push(temp);
temp = temp->left;
}
}
/** @return whether we have a next smallest number */
bool BSTIterator::hasNext() {
return !(s.empty());
}
/** @return the next smallest number */
int BSTIterator::next() {
TreeNode *curr = s.top(), *temp;
s.pop();
if (curr->right==NULL)
return curr->val;
temp = curr->right;
while (temp!=NULL){
s.push(temp);
temp=temp->left;
}
return curr->val;
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment