我有一个 binarySearch 树,我想创建一个方法 assignFirst。此方法应在树中找到具有最小值的节点,并相应地更新树的“第一个”属性。我有很多方法,但我不想将所有方法都包含在这里,因为我想保持简短和简单。因此,我将在该类中包含该类和一些功能。public class BinarySearchTree<E extends Comparable<E>>{private BSTNode<E> root; // root of overall treeprivate int numElements;private BSTNode<E> first;// post: constructs an empty search treepublic 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; }}
1 回答
不负相思意
TA贡献1777条经验 获得超10个赞
我想到了。我是这样写的。
private void assignFirst()
{
BSTNode<E> node = root;
while(node.left != null)
{
node = node.left;
}
first = node;
}
添加回答
举报
0/150
提交
取消