標籤:c++ leetcode 演算法
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, whereh is the height of the tree.
思路:依靠棧資料結構,然後中序遍曆的思想
class BSTIterator {public: BSTIterator(BinTree *root) { while(!st.empty()) sk.pop(); BinTree* temp=root; while(temp != NULL) { sk.push(temp); temp = temp->left; } } /** @return whether we have a next smallest number */ bool hasNext() { return sk.empty(); } /** @return the next smallest number */ int next() { BinTree* res = sk.top(); sk.pop(); BinTree* temp = res->right; while(temp != NULL) { sk.push(temp); temp = temp->left; } return res->value; }private: stack<BinTree*> sk;};
Binary Search Tree Iterator--LeetCode