java - 如何使用 BinarySearchTree 中的节点创建 allocateFirst 方法?

标签 java recursion binary-search-tree nodes

我有一个二叉搜索树,我想创建一个方法 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/

相关文章:

r - 用于检查列表是否按降序排序的除法征服算法

java - Java if 语句的递归

go - 如何编辑埋在递归结构中的数组

algorithm - 查找二叉搜索树 (BST) 的最大深度

Java 字符串比较/引用

java - Spring Boot 单元测试 Autowiring

java - 为什么使用 DataSource 而不是 XADataSource?

java - Lombok @Data 不会生成没有最终字段的空构造函数

c++ - 二叉树插入算法

algorithm - 使用 void 函数的二叉搜索树插入