Binary Search Tree Iterator

本文介绍了一种针对二叉搜索树(BST)的迭代器实现方法,该方法能够高效地找到并返回树中下一个最小值。通过不断向左遍历节点,并利用栈结构辅助记录,确保了平均O(1)的时间复杂度和O(h)的空间复杂度,其中h为树的高度。

题目描述:

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.


题目意思是设计一个迭代器,每次得到容器内最小的值。

一直往左子树走,就是最小值,然后看这个最小值有没有又子树且这个右子树之前没有被访问过,如果有右子树就接着往右子树的左子树走,没有的话弹出来看这个节点的父节点。

代码如下:

public class BSTIterator {

    Stack<TreeNode> stack;
	Set<TreeNode> visited;
	
	public BSTIterator(TreeNode root) {
		stack=new Stack<TreeNode>();
		visited=new HashSet<TreeNode>();
		stack.add(root);
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
		if(!stack.isEmpty()){
			return stack.peek()==null?false:true;
		}
    	return false;
    }

    public int next() {
    	TreeNode node=stack.peek();
        while(node.left!=null&&!visited.contains(node.left)){
    		stack.add(node.left);
    		node=node.left;
        }
        node=stack.pop();
        if(node.right!=null&&!visited.contains(node.right))
        	stack.add(node.right);
        visited.add(node);
        return node.val;
    }
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值