I am trying to implement a binary search tree with In order traversal. I am trying to print a series of numbers after each other to test it. It seems that it is sorting well, however it is printing dublicate numbers sometimes. Look at relevant pieces of my code:
Tree class and Methods:
public class Tree {
Node root;
public Tree(){
root = null;
}
public Node add(Node n, int value){
if(n== null){
n= new Node(value);
}else if(value < n.getValue()){
n.addLeftNode(add(n.getLeft(),value));
}else if(value > n.getValue()){
n.addRightNode(add(n.getRight(),value));
}
return n;
}
public static Node traverse(Node n){
Node result = new Node();
if(n != null){
if(n.getLeft() != null){
result = traverse(n.getLeft());
System.out.println(result.getValue());
}
result = n;
System.out.println(result.getValue());
if(n.getRight() != null){
result = traverse(n.getRight());
System.out.println(result.getValue());
}
}
return result;
}
}
This is what it's printing out:
0 0 1 1 3 4 4 5 6 7 7 8 10 11 12 12 12 15 15 15 15 15 15 15 16 18 18 20 21 22 22 22 22 23 27 28 28 28 29 34 35 43 43 43 43 43 43 43 44 45 45 55 56 59 66 75 75 75 75 75 75 76 76 76 78 88 89 89 90 90 90 98 98
Any clues? I'm guessing it's something with the traversal. Tried debugging it however I still couldn't find the issue. As you can see Nos are sorted at least.
When you traverse left or right, the call into traverse will print the left/right node. You don't have to print left and right separately.
if(n != null){
if(n.getLeft() != null){
result = traverse(n.getLeft());
// System.out.println(result.getValue());
}
result = n;
System.out.println(result.getValue()); // This prints the left and right via recursion into traverse(...)
if(n.getRight() != null){
result = traverse(n.getRight());
// System.out.println(result.getValue());
}
}
Traverse method should be:
void traverse(Node n) {
if(n == null)
return;
traverse(n.getLeft());
System.out.println(n.getValue());
traverse(n.getRight());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.