0

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 2

1

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.

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

2 Comments

Would this work if I was using a DefaultMutableTreeNode?
@user1995933 I haven't used a DefaultMutableTreeNode, but it looks like it would work if you used getChildAt() where I coded get()
0

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

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.