LeetCode - 解题笔记 - 173 - Binary Search Tree Iterator

这篇博客介绍了如何使用迭代方式实现二叉搜索树的中序遍历,重点在于不改变原有树结构的同时保持常数时间复杂度。解决方案详细阐述了Python和C++两种语言的代码实现,并分析了时间复杂度为O(N)和空间复杂度为O(H)。文中还讨论了Morris遍历法的适用场景及其对树结构的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值