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();
*/
该博客介绍了如何实现一个BSTIterator类,该类使用栈进行非递归遍历二叉搜索树,使得next()和hasNext()操作的时间复杂度达到平均O(1),同时仅使用O(h)的内存,其中h是树的高度。通过迭代的方式,依次返回树中的节点值,直至遍历结束。
1512

被折叠的 条评论
为什么被折叠?



