Printing specific path to a node in a binary tree

870 views Asked by At

I'm trying to use pre-order traversal to find a node in a binary tree made up of the characters a-z and A-Z, where going left is marked as "0" and going right is marked as "1", so that a correct output would look like "00" for a node that is two branches to the left. The nodes are not sorted.

So far I have this:

static String routeNum = "";      

private static String onePath(BinaryNodeInterface<Character> root, String route) {

    BinaryNodeInterface<Character> temp = root;
    if(temp != null){

    if(temp.hasLeftChild()){
      routeNum = onePath(temp.getLeftChild(),route+"0");

      }
      if(temp.hasRightChild()){
       routeNum = onePath(temp.getRightChild(), route+"1");

      }
    }

    System.out.print(route);
    return route;
}

The output indicates that I am getting to the right nodes but it doesn't print the path.

2

There are 2 answers

2
holtc On

You are never calling a print method. You can use:

System.out.println(route);

to print out the route String.

0
Dejan Bogatinovski On

Try this code without the static String routeNum = "";

private static String onePath(BinaryNodeInterface<Character> root, String route) {

BinaryNodeInterface<Character> temp = root;
if(temp != null){

if(temp.hasLeftChild()){
  route += "0";
  onePath(temp.getLeftChild(),route);

  }
  if(temp.hasRightChild()){
   route += "1";
  onePath(temp.getRightChild(), route);

  }
}

system.out.println(route);
return route;

}

Call this function with

String path = onePath(root, "");
Print(path);