Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a specific node in a non binary Tree?

Tags:

java

tree

I have a tree that contains multiple nodes. Each node has a parent node (or null in the case of the root), a name (name), and a HashTable (children) that maps the name of the child node to the child node object.

Given the string name of the node, I want to create a method that iterates through the tree to find the specific node and return it. If the node doesn't exist then return null.

I thought a recursive method would be best. So far I have this:

public Node findNode(Node n, String s) {
   if (n.name == s) {
       return n;
   } else {
       for (Node child: n.children.values()) {
            findNode(child, s);
       }
     }
}

I'm not sure exactly where to put the null statement.

like image 853
Ryan Smith Avatar asked Oct 27 '25 07:10

Ryan Smith


2 Answers

If a child has it, then return it. If not, then return null.

public Node findNode(Node n, String s) {
    if (n.name == s) {
        return n;
    } else {
        for (Node child: n.children.values()) {
            Node result = findNode(child, s);
            if (result != null) {
                return result;
            }
        }
    }
    return null;
}
like image 117
Nick Garvey Avatar answered Oct 28 '25 22:10

Nick Garvey


Here is Java 11+ version using Optional to search for the node.

public Optional<Node> search (Node node, String needle) {
    if (node.getValue().equals(needle)) {
        return Optional.of(node);
    } else {
        for (var child : node.getChildren()) {
            var result = search(child, needle);
            if (result.isPresent()) {
                return result;
            }
        }
    }

    return Optional.empty();
}
like image 32
Mihkel Selgal Avatar answered Oct 28 '25 22:10

Mihkel Selgal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!