I'm trying to display()
my binary tree with what's inside already but for some reason it's not working.
I'm getting nothing as an output.
Maybe my logic for the methods is off? I'm not quite sure.
Here's my Node.java
file:
(content missing)
Here's my BinaryTree.java
file:
public class BinaryTree {
public static Node root;
public BinaryTree() {
this.root = null;
}
public void insert(Node n, Student s) {
if(n != null) {
while(true) {
if(s.getLastName().compareTo(root.data) < 0) {
insert(n.left,s);
} else if(s.getLastName().compareTo(root.data) > 0) {
insert(n.right,s);
} else {
System.out.println("Error!!!!!");
}
}
}
}
public void display(Node root) {
if(root != null) {
display(root.left);
System.out.println(root.left);
display(root.right);
}
}
}
Here's my Student.java
file:
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);
}
public int compareTo(String s) {
int lengthOfLongestString = 0; // Length of longest string that we will base.
int i = 0; // Index of current string, will be incremented in for loop below.
int a = 0; // Index of
int b = 0;
if(lastName.length() < s.length()) { // If the string that's currently inside < incoming string
lengthOfLongestString = lastName.length(); // Then set the current string as the new length.
} else {
lengthOfLongestString = s.length(); // Else incoming string is the new length.
}
if(lastName.charAt(0) == s.charAt(0)) {
for(i = 0; i < lengthOfLongestString; i++) {
if(lastName.charAt(i) != s.charAt(i)) {
a++;
b++;
break;
}
}
if(i == lengthOfLongestString - 1) { // If i = length of last character of the string
return 0;
}
if(lastName.charAt(a) < s.charAt(b)) {
return -1;
}
}
return 1;
}
}
Here's my Main.java
file:
public class Main extends Student {
public Main(String first, String last, String ID) {
super(first, last, ID);
}
public static void main(String[] args) {
Student student = new Student("hi", "purple", "brown");
Student student2 = new Student("red", "purple", "now");
Node n = null;
BinaryTree bt = new BinaryTree();
bt.insert(BinaryTree.root, student);
bt.insert(BinaryTree.root, student2);
bt.display(BinaryTree.root);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…