Binary Search Tree Iterator
Description
Design an iterator over a binary search tree with the following rules:
Next() returns the next smallest element in the BST.
Elements are visited in ascending order (i.e. an in-order traversal)
next() and queries run in hasNext()O(1)O(1) time in average
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
* Example of iterate a tree:
* BSTIterator iterator = new BSTIterator(root);
* while (iterator.hasNext()) {
* TreeNode node = iterator.next();
* do something for node
* }
*/
public class BSTIterator {
/**
* @param root: The root of binary tree.
*/
Queue<TreeNode> queue = new LinkedList<TreeNode>();
public BSTIterator(TreeNode root) {
// do intialization if necessary
Iterator(root) ;
}
public void Iterator(TreeNode root){
if (root == null){
return ;
}
Iterator(root.left) ;
queue.offer(root) ;
Iterator(root.right) ;
}
/**
* @return: True if there has next node, or false
*/
public boolean hasNext() {
// write your code here
return !queue.isEmpty() ;
}
/**
* @return: return next node
*/
public TreeNode next() {
// write your code here
return queue.poll() ;
}
}
本文介绍如何设计一个二叉搜索树迭代器,满足O(1)平均时间复杂度的next()和hasNext()操作,用于在升序遍历过程中获取下一个最小元素。通过队列实现高效访问,适用于数据结构与算法学习者。
817

被折叠的 条评论
为什么被折叠?



