0

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?

7
  • What is the result you're getting? How is this being called? Where are you stuck. Commented Nov 16, 2012 at 10:14
  • so I this a binary search in which you print out the characters that you check? Commented Nov 16, 2012 at 10:14
  • @EdC im getting a StringIndexOutOfBounds Exception, Commented Nov 16, 2012 at 10:15
  • @The Cat: I only want to return the path taken to the target character from the root node. Commented Nov 16, 2012 at 10:16
  • @SimonHillary, I'm guessing you're calling this with an empty string to start with, i.e. "". Because of this the charAt(0) will exceed the end of the string (as it's currently length 0) Commented Nov 16, 2012 at 10:16

3 Answers 3

1

Your code is a little unclear to me. Is 'S' supposed to be the root payload? Also, you should really try to use more telling variable names.

public static String pathToNode(BTNode p, char target) {
    // termination rules
    if (p.data == target) {
       // success
       return p.data;       
    }
    // failure: p is not the target AND is a leaf.
    if (p.leftLink == null && p.rightLink == null) return null;

    // recursion: if p is in the subtree, this will find it.
    return (pathToNode(p.leftLink, target) == null) ? (p.data + pathToNode(p.rightLink), target) : (p.data + pathToNode(p.leftLink, target));

}

edit: This may, of course, return null after all, if the target is not in the tree. Also, I forgot to actually print the path. It's in there now.

Sign up to request clarification or add additional context in comments.

4 Comments

Sorry the 'S' was supposed to be target char, I was using it as a test case
Still don't see how target would fit in there. But anyhow, this traversion (travesty? ;) will have god-awful performance scaling with all those String concatenations. Keep that in mind.
Well tbh that was my fifth "solution" to the problem and I think I was getting all messed up. The binary tree only has about 50 nodes so performance isn't a major concern!
in that case, impress your coworkers with some corkscrew-straight thinking: Write a permutator that iterates all possible permutations of 0..5 characters. Append the target character to each string. Then for each string, try to traverse the tree in order of the characters. Return the string for which that actually worked. You'll be the hero in the office ;) Even easier if you take akaIDIOT's 'res + > + data' approach, you only have to check one direction then.
0

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.data to res in the recursive call should make sure the 'current' step is saved in the res variable:

if (p.data == target) {
    res = res + p.data;
    System.out.println(res);
} else {
    pathToNode(p.leftLink, target, res + p.data);
    pathToNode(p.rightLink, target, res + p.data);
}

This way, you're using a traditional base case + recursive case common to recursive algorithms.

4 Comments

Many thanks, this works with a slight amendment at the beginning, first checking if p == null and if so, returning. Avoids null pointer exception!
@SimonHillary that entirely depends on how you call your method, which you didn't specify :) Also, don't forget to accept the answer you think answers your question best ;)
Sorry my fault! any idea how to modify this to print out either 'left' or 'right' based on whether traversed to left or right node in order to get to the target?
@SimonHillary you could add that to the recursive call that goes either left or right; use res + '<' + p.data or res + '>' + p.data.
0

I think you are trying to find the path from the root. Also I am assuming the tree will have only one path to on target. I mean same element cant be in different places in the tree.

This code will work,

public static void pathToNode(BTNode p, char target, String res){
    if(p.data == target){
        res += p.data;
        System.out.println(res);
        return;
    }
    else{
        if(res==null){
           res="";
        }
        res += p.data;
        pathToNode(p.leftLink, target, res);
        pathToNode(p.rightLink, target, res);
    }
}

But this will be very inefficient and memory cost easy solution. Please read more about tree traversal to have a good solution.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.