Leetcode 173. Binary Search Tree Iterator

本文介绍了一种遍历二叉搜索树的方法,通过使用栈结构实现了一个迭代器类BSTIterator,该迭代器能够按顺序返回树中节点的值。文章详细解释了迭代器的实现原理,包括初始化时如何遍历左子树并将节点压入栈中,以及如何在每次调用next方法时返回下一个最小元素。

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

文章作者:Tyan
博客:noahsnail.com  |  优快云  |  简书

1. Description

Binary Search Tree Iterator

2. Solution

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
private:
    stack<TreeNode*> index;
public:
    BSTIterator(TreeNode *root) {
        traverseLeft(root);
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !index.empty();
    }

    /** @return the next smallest number */
    int next() {
        TreeNode* current = index.top();
        index.pop();
        traverseLeft(current->right);
        return current->val;
    }

    void traverseLeft(TreeNode* root) {
        TreeNode* current = root;
        while(current) {
            index.push(current);
            current = current->left;
        }
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */

Reference

  1. https://leetcode.com/problems/binary-search-tree-iterator/description/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值