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() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
參考:https://oj.leetcode.com/discuss/20001/my-solutions-in-3-languages-with-stack
解題思路:用一個stack儲存從根節點開始的所有左孩子,每次調用next()就從stack裡面pop一個元素,並將以這個節點的右孩子為根節點的子樹重複同樣的過程。
這個演算法滿足O(h)的空間複雜度,hasNext()的時間複雜度滿足O(1),儘管next()的時間複雜度為O(h),但是這個演算法的處理過程仍然值得學習。
C++代碼實現如下:
/** * 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(); */
該演算法的時間效能表現如下: