0

I am trying to print a binary search tree and get the following output:

-19->4->5->6->259->

How do I adjust the traverse function so that the last arrow is not printed in the output?

I am using this code inside the main function:

Tree x = new Tree(5);
x.add(6);
x.add(4);
x.add(259);
x.add(-19);
x.traverse(x);

The Tree class is below:

public class Tree {
    Tree root;
    Tree left;
    Tree right;
    int value; 

public Tree(int value){
    this.value=value;
    this.left=null;
    this.right=null;
}

boolean add(int value){

    if (value == this.value)
        return false;
    else if (value <this.value) {
        if (left == null) {
            left = new Tree(value);
            return true;
        } else
            return left.add(value);
    } else if (value > this.value) {
        if (right == null) {
            right = new Tree(value);
            return true;
        } else
            return right.add(value);
    }
    return false;

}

void traverse(Tree root){

    if (root.left != null){
        traverse(root.left);
    }       

    System.out.printf("%d",root.value);
    System.out.printf("->");
    if (root.right != null){
        traverse(root.right);
    }
}
}
Rajan
  • 43
  • 7

2 Answers2

0

You want to avoid printing the -> only for the last, i.e., biggest, element. So, you want to not print it if the node has no right child and all nodes leading to it were "right" nodes.

void traverse(Tree root, boolean allRight){

    if (root.left != null){
        traverse(root.left, false);
    }       

    System.out.printf("%d",root.value);
    if(!allRight || root.right != null)
        System.out.printf("->");
    if (root.right != null){
        traverse(root.right, allRight);
    }
}

Also, you would now call it like this : x.traverse(x, true).

Pradhan
  • 16,391
  • 3
  • 44
  • 59
0

Here is another version

public boolean traverse(TreeNode root){

    if (root.left != null){
        traverse(root.left);
        System.out.printf("->");

    }       

    System.out.printf("%d",root.value);

    if (root.right != null){
        System.out.printf("->");
        traverse(root.right);           
    }

    return true;
}
Rajan
  • 43
  • 7