【发布时间】:2017-04-30 12:09:30
【问题描述】:
我想知道为什么我的display() 方法即使在将项目插入到我的二叉树之后也会打印基本情况。我正在尝试比较学生的姓氏。我想要的只是显示我的树,以便我可以确认insert() 有效。
这是我的Node.java 文件:
class Node {
Student data;
Node left;
Node right;
public Node(Student data) {
this.data = data;
left = null;
right = null;
}
}
这是我的BinaryTree.java 文件:
public class BinaryTree {
public Node root;
public void insert(Student s) {
root.left = new Node(s);
root.right = new Node(s);
root = insert(s,root);
}
private Node insert(Student s, Node t) {
if(t == null) {
t = new Node(s);
return t;
}
else {
if(s.getLastName().compareTo(t.data.getLastName()) < 0) {
t.left = new Node(s);
t.left = insert(s,t.left);
return t.left;
} else if(s.getLastName().compareTo(t.data.getLastName()) > 0) {
t.right = new Node(s);
t.right = insert(s,t.right);
return t.right;
}
}
return t;
}
public void display(Node root) {
if(root == null) {
System.out.println("Nothing found.");
} else if(root != null) {
display(root.right);
System.out.println(root.data);
display(root.left);
}
}
}
这是我的Student.java 文件:
public class Student {
private String firstName;
private String lastName;
private String id;
public Student(String first, String last, String Identification) {
firstName = first;
lastName = last;
id = Identification;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public boolean equals(String studentId) {
return id.equals(studentId);
}
}
这是我的Main.java 文件:
public class Main {
public static void main(String[] args) {
Student student = new Student("hi", "bye", "testing");
Student student2 = new Student("out", "some", "names");
BinaryTree bt = new BinaryTree();
bt.insert(student);
bt.insert(student2);
bt.display(bt.root);
}
}
这是我在控制台中的output:
Nothing found.
【问题讨论】:
-
if(t == null) { root = t; }您将根设置为null -
您的显示逻辑也有问题,因为您在遇到基本情况时调用了
System.exit(0)。这将杀死你的整个程序。您可能只想返回。 -
@MariaInesParnisari 但是然后我递归地插入到右边和左边。
-
由于根始终为空,因此不会进入其他情况。
root = insert(s, root) -
我发现插入和遍历都有问题。让插入工作,然后担心显示。
标签: java algorithm data-structures binary-tree nodes