LeetCode-Binary Search Tree Iterator-解题报告

原题链接https://leetcode.com/problems/binary-search-tree-iterator/

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, whereh is the height of the tree. 


嗯,  开始没注意要O(h)的额外空间要求。


可以这样,在构造函数中我定义了一个双端队列,应为要用到在队列前插入和删除的操作。

首先我们在构造函数中先压入根节点。

在hasnext中  我们将节点的一直向左的点压入按照层次的顺序压入队列中,为什么?  最小的一定是最左边的 如果存在的话。为了防止相同节点的入队两次,入队一次便把left置为NULL

在next中,保存队首元素,并出队,如果队首元素的右节点存在,则压入队首。

队列中的元素个数 最多为 数的高度 即额外空间为O(h)

next() O(1)

hasnext() 因为一直向左 O(h)


实在没想到O(1)的hasnext(), 

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
	BSTIterator(TreeNode *root) {
	    if (root != NULL)
		    val.push_front(root);
	}
	/** @return whether we have a next smallest number */
	bool hasNext() {
		if (val.empty())return false;
		TreeNode* Node = val.front();
		left(Node->left);
		Node->left = NULL;
		return val.size();
	}

	/** @return the next smallest number */
	int next() {
		TreeNode* Node = val.front();
		val.pop_front();
		if (Node->right != NULL)val.push_front(Node->right);
		return Node->val;
	}
private:
	void left(TreeNode* root)
	{
		if (root == NULL)return;
		val.push_front(root);
		left(root->left);
		root->left = NULL;
	}
	deque<TreeNode*>val;
};

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值