Created
November 3, 2018 16:13
-
-
Save z0marlin/6a22a1ce2daefb5ef2e033f15248aff7 to your computer and use it in GitHub Desktop.
WEC Codebuddy week5 3rd sem solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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