So I am reading from a file(Consist of name and salary) and inserting into a tree. After that, I am doing a search method. It's working and printing true if the node exists. How do I print the actual name and salary just by searching by salary? Here is my search method:
public boolean find(int salary) {
Add current = root;
while (current != null) {
if (current.getSalary() == salary) {
return true;
} else if (current.getSalary() > salary) {
current = current.getLeft();
} else {
current = current.getRight();
}
}
return false;
}
And Here is my main method:
public static void main(String[] args) throws IOException {
BinaryTree bt = new BinaryTree();
bt.readfile();
bt.print(bt.root);
System.out.println();
System.out.println("Find method: return true if a node exits ,else return flase");
System.out.println(bt.find(8900));`
If find()
returns a node, write a toString()
method for the node such that the
name is expressed.
Example:
@Override
public String toString(){
return this.name + " " + this.salary;
}
Why this works:
When the System.out.println()
calls on your node it will automatically call on the memory address. If you override this call with your custom method you can define what variables are printed out.