Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find path to node in Tree?

Tags:

java

tree

I have a tree class that looks like:

Class Tree {
   Node root;
   Node curNode;
   public List<String> find(String value) {
      if (curNode == null) curNode = root;
        for (Node child : curNode.children) {
            if (found == false) {
                if (child.data.equals(value)) {
                    // if it finds it return the path to this node.
                }
                curNode = child;
                findDFS(value);
            }
        }
   }


class Node {
   List<Node> children;
   String data;
}

Where the tree root contains pointers to children nodes which point to other children etc etc. What I'm having problems with is once it finds the node, I need to return the the path to that node.

like image 476
user2998228 Avatar asked Nov 27 '13 02:11

user2998228


1 Answers

passing a list tracking the path, once find the node, exit the recursion and fill the path one by one.

    Boolean Search(Node node, String value, List<Node> track)
    {
        if (node == null) return false;

        if (node.data.equals(value))
        {
            track.add(node);
            return true;
        }

        for(Node child : node.children)
        {
            if (Search(child, value, track)
            {
                track.add(0, node);
                return true;
            }
        }

        return false;
    }
like image 163
Easton L. Avatar answered Oct 01 '22 00:10

Easton L.