Solution 1
封装的二叉树中序遍历,根据题目限制,需要使用迭代实现方法(还是应该学习一下迭代写法)。
至于Morris遍历法,考虑到其会修改原有树的结构,不符合迭代器的设计。
- 时间复杂度: O ( 1 ) O(1) O(1),整体遍历时间应该是 O ( N ) O(N) O(N),其中 N N N为输入树的结点个数,因而单个原子操作能够达到常数时间复杂度
- 空间复杂度: O ( H ) O(H) O(H),其中 H H H为树的最大深度,栈的实际占用
/**
* 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:
BSTIterator(TreeNode* root) {
this->root = root;
this->target = root;
}
int next() {
while (this->target != nullptr) {
this->nodes.push(this->target);
this->target = this->target->left;
}
this->target = this->nodes.top();
this->nodes.pop();
int ans = this->target->val;
this->target = this->target->right;
return ans;
}
bool hasNext() {
bool ans = this->target != nullptr || !this->nodes.empty();
return ans;
}
private:
TreeNode* root;
TreeNode* target;
stack <TreeNode*> nodes;
};
/**
* 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();
*/
Solution 2
Solution 1的Python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.root = root
self.target = root
self.nodes = list()
def next(self) -> int:
while self.target is not None:
self.nodes.append(self.target)
self.target = self.target.left
self.target = self.nodes[-1]
self.nodes.pop()
ans = self.target.val
self.target = self.target.right
return ans
def hasNext(self) -> bool:
ans = self.target is not None or len(self.nodes) > 0
return ans
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()