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.
How to find a node in a tree given a path
449 Views Asked by user1995933 At
2
There are 2 best solutions below
2

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.
You can do this Save and process all child nodes from root into stack Then start poping each child node and doing same with it recursively