Binary Search Tree Iterator LeetCode solution in C++
1// TC O(1) and O(H) Space23// MIMIC inorder4class BSTIterator {5public:6stack<TreeNode *> stk;7BSTIterator(TreeNode *root) {8pushAll(root);9// left is done10}1112int next() {13// root handled14TreeNode *node = stk.top();15int ans = node->val;16stk.pop();1718// right handled19pushAll(node->right);2021return ans;22}2324bool hasNext() {25return stk.size() != 0; // stk is empty then no next to show simple26}2728void pushAll(TreeNode *root) {29// left part - as inorder is like Left left left, once a root is done then30// check right31while (root != NULL) {32stk.push(root);33root = root->left;34}35}36};