Binary Search Tree Iterator
Description
Design an iterator over a binary search tree with the following rules:
- Elements are visited in ascending order (i.e. an in-order traversal)
next()
andhasNext()
queries run in O(1) time in average.
Example For the following binary search tree, in-order traversal by using iterator is [1, 6, 10, 11, 12] 10 / \ 1 11 \ \ 6 12
Challenge Extra memory usage O(h), h is the height of the tree.
- We are here, indorder traversal
Super Star: Extra memory usage O(1)
- Use binary search O(logn) S(1)
Link
Method
- x
- x
Example
- 1
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } * Example of iterate a tree: * BSTIterator iterator = BSTIterator(root); * while (iterator.hasNext()) { * TreeNode * node = iterator.next(); * do something for node */ class BSTIterator { public: // @param root: The root of binary tree. BSTIterator(TreeNode *root) { // write your code here TreeNode* tmp = root; while (tmp) { stk.push(tmp); tmp = tmp->left; } } // @return: True if there has next node, or false bool hasNext() { // write your code here return !stk.empty(); } // @return: return next node TreeNode* next() { // write your code here next_min = stk.top(); stk.pop(); TreeNode* tmp = next_min->right; while (tmp) { stk.push(tmp); tmp = tmp->left; } return next_min; } private: // TreeNode* src; TreeNode* next_min; stack<TreeNode*> stk; };
Similar problems
x
Tags
x