java - 为 BST 支持的符号表创建 Iterable
问题描述
对于分配,我需要创建一个迭代,其中包含由二叉搜索树支持的符号表的所有键。我熟悉如何为链表执行此操作,但似乎无法在网上找到任何有关如何为 BST 执行此操作的示例。例如,对于链表,我会使用如下内容:
public Iterable<Key> keys() {
Queue<Key> queue = new Queue<Key>();
for (Node x = first; x != null; x = x.next)
queue.enqueue(x.key);
return queue;
}
但我不太确定如何转换它,所以它保存了我 BST 的所有密钥。有人可以提供指导或链接到涵盖该主题的来源吗?
解决方案
如果要先向左遍历,可以使用栈来实现。
static class Node<T> {
T value;
Node<T> left, right;
Node(T value, Node<T> left, Node<T> right) {
this.value = value;
this.left = left;
this.right = right;
}
}
和
static class BST<T> implements Iterable<T> {
Node<T> root;
public BST(Node<T> root) {
this.root = root;
}
@Override
public Iterator<T> iterator() {
return new Iterator<>() {
Deque<Node<T>> stack = new LinkedList<>();
{ pushAllLeft(root); }
private void pushAllLeft(Node<T> node) {
for ( ; node != null; node = node.left)
stack.push(node);
}
@Override
public boolean hasNext() {
return !stack.isEmpty();
}
@Override
public T next() {
Node<T> current = stack.pop();
pushAllLeft(current.right);
return current.value;
}
};
}
}
和
public static void main(String[] args) {
BST<Integer> bst = new BST<>(
new BST.Node<>(3,
new BST.Node<>(1,
new BST.Node<>(0, null, null),
new BST.Node<>(2, null, null)),
new BST.Node<>(5,
new BST.Node<>(4, null, null),
new BST.Node<>(6, null, null))));
for (int n : bst)
System.out.println(n);
}
输出:
0
1
2
3
4
5
6
推荐阅读
- c++11 - 如何使用 std::chrono 找到剩余的冷却时间?
- mysql - 在mysql中组合多行的快速方法
- laravel - 在两种关系中查询 Laravel 7
- javascript - 如何在 ReactJs 的复选框中显示星期几
- protractor - 检查量角器黄瓜框架中是否存在元素
- c++ - 我有两组数据相互映射。有没有办法根据另一个变量的值检查相应变量的值?
- arrays - 如何在c中水平查找二维数组(10x2)中的重复值
- java - EditText 没有出现在模拟器中
- matomo - 当参数包含大写字母时,Matomo Track 事件不起作用
- php - 如何将txt文件中的内容获取到数组中