LeetCode [Tree]: Binary Search Tree Iterator, leetcodeiterator
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling next () will return the next smallest number in the BST.
Note: next () and hasNext () shocould run in average O (1) time and uses O (h) memory, where h is the height of the tree.
Reference: https://oj.leetcode.com/discuss/20001/my-solutions-in-3-languages-with-stack
Solution: Use a stack to store all left children starting from the root node. Each time you call next (), pop an element from the stack, and repeat the same process for the subtree with the right child of the node as the root node.
This algorithm satisfies the space complexity of O (h), and the time complexity of hasNext () satisfies O (1). Although the time complexity of next () is O (h ), however, the processing process of this algorithm is still worth learning.
The C ++ code is implemented as follows:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class BSTIterator {private: stack<TreeNode *> nodeStack; void pushAll(TreeNode *root) { for (TreeNode *node = root; node != nullptr; node = node->left) { nodeStack.push(node); } }public: BSTIterator(TreeNode *root) { pushAll(root); } /** @return whether we have a next smallest number */ bool hasNext() { return !nodeStack.empty(); } /** @return the next smallest number */ int next() { TreeNode *node = nodeStack.top(); nodeStack.pop(); pushAll(node->right); return node->val; }};/** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
The time performance of this algorithm is as follows: