Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- /*
- Logic:
- We will use a stack and push the root node and it's all left elements in stack in constructor.
- next function want the next element of inorder so return the top element of stack and push the
- right element of top element of stack and push all the left elements
- hasNext : it return true if there is next element in inorder.
- */
- class BSTIterator {
- stack<TreeNode*> st;
- public:
- BSTIterator(TreeNode* root) {
- while(root){
- st.push(root);
- root=root->left;
- }
- }
- int next() {
- TreeNode *temp=st.top();
- st.pop();
- int res=temp->val;
- if(temp->right){st.push(temp->right);temp=temp->right;
- temp=temp->left;
- while(temp){
- st.push(temp);
- temp=temp->left;
- }
- }
- return res;
- }
- bool hasNext() {
- if(st.size()) return true;
- return false;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement