实现二分查找树的迭代器(Binary Search Tree Iterator )

本文介绍如何使用中序遍历来实现二叉搜索树(BST)的迭代器,重点阐述了如何通过栈结构在O(1)平均时间复杂度下完成操作,同时讨论了内存使用的优化。

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

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.

Solutions:

首先想到的要用中序遍历。

O(n) memory的算法:

class BSTIterator {
public:
    BSTIterator(TreeNode *root) {
        this->root = root;
		InOrderSearch(root);		
		if(root == NULL) {
			return;
		}
    }
	void InOrderSearch(TreeNode *t) {
		if(t == NULL) {
			return;
		}
		if(t->left != NULL) {
			InOrderSearch(t->left);
		}
		Q.push(t);
		if(t->right != NULL) {
			InOrderSearch(t->right);
		}
	}

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

    /** @return the next smallest number */
    int next() {
		int ret=Q.front()->val;
		Q.pop();
        return ret;
    }
private:
	TreeNode *root;
	queue<TreeNode*> Q;
};
O(n)算法:

不用预先遍历所有节点。用一个栈保存即将要访问的节点,先入栈的后访问。每当访问一个节点时,将该节点出栈,并将其右孩子及其左链一并入队列。

从而可以实现动态更新栈内容,实现正确的中序访问次序。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值