I am trying to recursively display the path taken to a given node in a binary tree where the method will output the path needed in the following way: “left, right, left”.
Here is what I have so far:
public static void pathToNode(BTNode p, char target, String res){
if(p.data == target){
res = res + p.data;
System.out.println(res);
return;
}else if(res != null){
if(res.charAt(0) == 'S'){
res = res + p.data;
}
}else{
pathToNode(p.leftLink, target, res);
pathToNode(p.leftLink, target, res);
}
}
This code is intended to just print out the path like so: “ABCD”.
Having done this I intend on making the method print out either left of right based on the correct option for each node traversal. Any Ideas?
You’re printing the result when you find the target you’re looking for in the first if clause. Alternatively, you should try both the left and the right branches of the tree, what you (almost, you’re doing left twive) do in the last clause.
I’m not sure what the second clause is supposed to be doing, but removing it and adding
p.datatoresin the recursive call should make sure the ‘current’ step is saved in theresvariable:This way, you’re using a traditional base case + recursive case common to recursive algorithms.