173. Binary Search Tree Iterator
1.問題
實作BST的迭代器, constructor, next, hasNext

2.想法
用stack儲存BST的left主線上的node
last in first out的特性
BST的left主線是最小值, 而left主線上node的每一個right node的left主線又是另一個list, 其大小介於該node的以及node的上一次中
因此每次pop stack的元素時, 要再將top的right以及其left主線上的元素全部加入
3.程式碼
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
TreeNode * curr = root;
while (curr) {
st.push(curr);
curr = curr->left;
}
}
/** @return whether we have a next smallest number */
bool hasNext() {
return !st.empty();
}
/** @return the next smallest number */
int next() {
int val = st.top()->val;
TreeNode* node = st.top()->right;
st.pop();
while (node) {
st.push(node);
node = node->left;
}
return val;
}
private:
stack<TreeNode*> st;
};
/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
4.Performance

Last updated