如何使用 BinarySearchTree 中的节点创建 assignFirst 方法?

我有一个 binarySearch 树,我想创建一个方法 assignFirst。


此方法应在树中找到具有最小值的节点,并相应地更新树的“第一个”属性。


我有很多方法,但我不想将所有方法都包含在这里,因为我想保持简短和简单。因此,我将在该类中包含该类和一些功能。


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;

    }

}


汪汪一只猫
浏览 57回答 1
1回答

不负相思意

我想到了。我是这样写的。private void assignFirst(){&nbsp; &nbsp; BSTNode<E> node = root;&nbsp; &nbsp; while(node.left != null)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; node = node.left;&nbsp; &nbsp; }&nbsp; &nbsp; first = node;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java