I have a TreeModel in java and I'm given a path to find to check if the path exists. For example /dir1/dir2/dir3/ is an existing path in my tree. My tree is non binary. How would I approach this? My idea was to have the function take a DefaultMutableTreeNode then check if node has the same name as the first directory in my path and so on for the rest of the directories. My problem is how to change to the next string and the next node recursively. Should my function be recursive, iterative etc.. Any help would be great! Thanks in advance.
2 Answers
Assuming you have a typical tree, where each element of your path is the key to the next node, something like this should work when called on the root node:
public boolean hasPath(String path) {
Node node = this;
for (String key : path.split("/")) {
node = node.get(key);
if (node == null)
return false;
}
return true;
}
It's iterative and therefore easier to understand than going down the rabbit hole of recursion. It's also more efficient.
2 Comments
user1995933
Would this work if I was using a DefaultMutableTreeNode?
Bohemian
@user1995933 I haven't used a
DefaultMutableTreeNode, but it looks like it would work if you used getChildAt() where I coded get()