javarecursiontreenodetree-nodes

Trouble checking for a valid path (string) being entered into a tree


I've created a TreeNode class which holds an ArrayList of tree nodes (named branch) and I want to add new branches to the tree by user entered paths. An example path being /Monkey/King/Bar where each of those would ideally be an existing branch with the exception of the last one (Bar would be the branch I'd like to add to King). Temp is a global variable I use for adding new branches to the tree and with recursion I'm trying to move down the path validating that each branch is a child of the previous branch and I'm having some trouble getting it to work. This is what I have so far and was wondering if it has something to do with not setting the parent when I re-declare the temp TreeNode. Any help would be appreciated and if anything I said is too vague please ask for clarification.

TreeNode tree = root;
boolean valid = false;
String y = x; //User entered path
for (int i = 0; i < x.length(); i++)
{
  if (x.charAt(i) == '/')
  {
      for (int j = 0; j < tree.branch.size(); j++){
        if (tree.branch.get(j).toString().equals(y)){
            System.out.println(temp.value);
            tree = tree.branch.get(j);
            temp = tree;
            valid = true;
        }
        else
          valid = false;
      }
      y = "";
}

Solution

  • It looks like you're trying to traverse the tree and add a node (or a branch) at the end if the path exists or something similar?

    I think the problem is mainly how you're handling the string, not the nodes. You're not actually getting the parts of the path, you're doing the whole string, then nothing.

    First, a better way to work with string in this way is to use String.split

    String[] pathparts = String.split("/");
    

    Next, you need to know if it's the part of the strign

    for(int i=0;i<pathparts.length-1;i++){ // we don't want the last string
         // your code with .get(pathparts[i]) 
    }
    

    It looks like you're handling the rest of the code correctly if my assesment of what you're doign is correct.