實現 BST 迭代器,支持 next() 返回下一個最小值,hasNext() 判斷是否有下一個。要求均攤 O(1) 時間,O(h) 空間 (h 為樹高)。
中序遍歷 BST 即為升序輸出。用棧維护從根到當前最小節點的路徑:
next():彈出棧頂 (最小),將其右子樹的左鏈入棧hasNext():棧非空即有下一個class BSTIterator {
stack<TreeNode*> stk;
void pushLeft(TreeNode* node) {
while (node) {
stk.push(node);
node = node->left;
}
}
public:
BSTIterator(TreeNode* root) { pushLeft(root); }
bool hasNext() { return !stk.empty(); }
int next() {
TreeNode* cur = stk.top(); stk.pop();
pushLeft(cur->right);
return cur->val;
}
};
pushLeft 封裝重複邏輯,構造函數與 next() 復用此題是「棧模擬遞歸」的教科書級應用,理解中序遍歷的棧幀變化是關鍵。