我有一个二叉搜索树,我想创建一个方法 allocateFirst。
此方法应该找到树中具有最小值的节点,并且 相应地更新树的“first”属性。
我有很多方法,但我不想将所有方法都包含在这里,因为我想让它简短明了。 因此,我将包含该类以及该类中的一些功能。
public class BinarySearchTree<E extends Comparable<E>>
{
private BSTNode<E> root; // root of overall tree
private int numElements;
private BSTNode<E> first;
// post: constructs an empty search tree
public BinarySearchTree()
{
this.root = null;
this.numElements = 0;
}
private void assignFirst()
{
if (root.left == null)
{
first.data = root.data;
}
else
{
first.data = root.left.data;
}
}
public class Iterator
{
private BSTNode<E> currentNode;
public Iterator()
{
currentNode = first;
}
public boolean hasNext()
{
return currentNode != null;
}
public E next()
{
E value = currentNode.data;
currentNode = currentNode.next;
return value;
}
}
private static class BSTNode<E>
{
public E data;
public BSTNode<E> left;
public BSTNode<E> right;
public BSTNode<E> parent;
public BSTNode<E> next;
public BSTNode(E data)
{
this(data, null, null, null, null);
}
public BSTNode(E data, BSTNode<E> left, BSTNode<E> right, BSTNode<E> parent, BSTNode<E> next)
{
this.data = data;
this.left = left;
this.right = right;
this.parent = parent;
this.next = next;
}
}
}
我更新了我的方法,如下所示。我仍然不确定这是否是正确的做法。
private void assignFirst()
{
if (first.left != null)
{
first = first.left;
}
else
{
first = root;
}
}
最佳答案
我明白了。我是这样写的。
private void assignFirst()
{
BSTNode<E> node = root;
while(node.left != null)
{
node = node.left;
}
first = node;
}
关于java - 如何使用 BinarySearchTree 中的节点创建 allocateFirst 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55911116/