next() 和 hasNext() 操作均摊时间复杂度为 O(1) ,并使用 O(h) 内存的做法。其中 h 是树的高度,O(1)为平均时间复杂度。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// 拆分树的非递归遍历
class BSTIterator {
public:
stack<TreeNode*> stk;
BSTIterator(TreeNode* root) {
while (root) {
stk.push(root);
root = root->left;
}
}
int next() {
TreeNode* root = stk.top();
int x = root->val;
stk.pop();
root = root->right;
while (root) {
stk.push(root);
root = root->left;
}
return x;
}
bool hasNext() {
return !stk.empty();
}
};
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator* obj = new BSTIterator(root);
* int param_1 = obj->next();
* bool param_2 = obj->hasNext();
*/