二叉搜索树布尔值 return 类型

Binary search tree boolean return type

这是一个在我的二进制搜索中添加节点的函数 tree.How 如果此树尚未包含指定的元素,我可以将其重新格式化为 return true 吗?

private Node insertNode(Node root, Student student) {
    if (root == null) {
        root = new Node(student);
    }
    int comp;
    if (Comparator != null) {
        comp = Comparator.compare(student, root.value);
    } else {
        comp = student.compareTo(root.value);
    }

    if (comp < 0) {
        root.left = insertNode(root.left, student);
    } else if (comp > 0) {
        root.right = insertNode(root.right, student);
    }
    return root;
}

如果需要,您需要大量重构此代码。

先搜索节点可能会简单很多,如果存在,returnfalse,如果不存在,运行这段代码然后returntrue。类似于:

// Keep `insertNode`, as is, unchanged, except name it `createNode`.
// Make sure to include in its docs that it doesn't create
// if the `student` record already exists in the tree.

private boolean insertNode(Student student) {
    if (search(this.root, student)) return false;
    createNode(this.root, student);
    return true;
}

作为一般规则,您在编写递归算法时几乎总是需要 2 方法。实际的递归方法,它是 private 并且有无意义的参数,至少从 API 的角度来看,以及一个 public 的方法,它知道必须传递哪些初始值那些论点。

例如,在您的代码中,您需要将 Node root 提供给 insertNode。从 insertNode 递归过程的角度来看,这是至关重要的。然而,从外界的角度来看,这毫无意义。如果我正在为显示所有学生的 GUI 前端编写代码,为什么 I 需要提供节点?您的对象肯定是 StudentTree 或诸如此类的类型, 毫无疑问知道根节点。 (它应该,例如,通过成为一个领域,如果现在不是的话)。

如果您已经设置了双重方法,您还可以根据需要更改 return 类型。

要明确的是,如果不制作2种方法,这是不可行的。充其量你可以 return,而不是 Node,一些 return 节点和布尔值的组合对象,然后所有调用者都可以解压缩它,但这需要大量的努力(制作一个 class 来表示这个,并且 每次 你调用 insertNode,包括 insertNode 本身,将 Node 对象解压出来)。