你能帮我打印一个用二叉搜索树制作的家谱吗?

问题描述 投票:0回答:1

我已经开始学习二叉搜索树了,我做了一个练习,要求我用二叉搜索树制作一个家谱。

我已经创建了它,但我遇到了一些问题,所以我不确定它是否正确,它有四个变量:name,surname,father和mother,这使得这棵树与我拥有的所有例子完全不同已经看过。我将在下面的代码中展示我已经完成的工作:

//I have created a class Ancestor
public class Ancestor {
    String name;
    String surname;
    Ancestor father;
    Ancestor mother;

public Ancestor (String name, String surname){
    this.name = name;
    this.surname = surname;
    father = null;
    mother = null;
}

public void printAncestor() {
    System.out.println("Ancestors:"+"");
}

public void postOrder (Ancestor a) {
    if (a == null) {
        return;
    }

    else {
        postOrder(a.mother);
        postOrder(a.father);
        a.printAncestor();
    }
  }
}

//Another class familyTree
public class familyTree {
    static Ancestor root = null;

static void insertAncestor (String n, String s){
    Ancestor temp = root;
    Ancestor prev = null;
    boolean notFound = true;

    while (temp != null && notFound){
        if (temp.name.equals(n) && temp.surname.equals(s)){
            notFound = false;
            break;
        }
        else if (n.compareTo(n)<0 && s.compareTo(s)<0){
            prev = temp;
            temp = temp.mother;
        }
        else {
            prev = temp;
            temp = temp.father;
        }
    }

    if (notFound){
        Ancestor a = new Ancestor(n, s);
        if (prev == null) {
            root = a;
        }
        else if (n.compareTo(n)<0 && s.compareTo(s)<0){
            prev.mother = a;
        }
        else {
            prev.father = a;
        }
     }
  }
}

//And I have tried to create a family tree in the main class
public class Main {

public static void main(String[] args) {
// write your code here
    familyTree f = new familyTree();

    f.insertAncestor("Adam", "H");
    f.insertAncestor("Charles", "B");
    f.insertAncestor("Mary", "C");
    f.insertAncestor("Matthew", "W");
    f.insertAncestor("Jane", "X");

 }
}

我想知道我的课程是否有意义,因为它们没有显示任何错误,但它们仍然可能令人困惑。我还想知道我是否正确创建了家谱,并根据我打印家谱的方法,我将如何打印它?我试过这样的:

f.postOrder();

但它没有成功。所以我不确定是什么问题。正如我所说,变量(名称,姓氏,父亲,母亲)与互联网和其他材料上的大多数示例不同,这让我感到困惑。无论如何,我提前感谢你们。

java binary-search-tree
1个回答
1
投票

所以有几点。首先是一个小问题:使用更具描述性的变量名称可以更好地服务。您有一个方法签名,如下所示:

static void insertAncestor (String n, String s)

好吧,ns没有做出好的参数名称。我可以从上下文中看到n是为了这个名字,而s是为了这个名字,但为什么不把它们称为namesurname

在实际的代码功能方面,这条线立即跳出来:

else if (n.compareTo(n)<0 && s.compareTo(s)<0){

您将ns与自己进行比较,因此比较将始终为0,并且if块将始终被跳过,并将落入else块。

那里有什么功能?你是如何确定是否要离开母亲的一侧或父亲的一侧?你怎么表明“这个新祖先应该作为根的母亲的母亲的母亲插入”?可能是二叉树不是您应该首先使用的数据结构。并非每种数据结构都适用于所有问题。

© www.soinside.com 2019 - 2024. All rights reserved.