Find path to node in Tree?

后端 未结 3 1840
暗喜
暗喜 2020-12-17 05:00

I have a tree class that looks like:

Class Tree {
   Node root;
   Node curNode;
   public List find(String value) {
      if (curNode == null)         


        
相关标签:
3条回答
  • 2020-12-17 05:37

    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;
        }
    
    0 讨论(0)
  • 2020-12-17 05:48

    If the nodes only point to their children, you'll need to keep track of each path on the way down. As mentioned in comment, you can do this with your own stack or with recursion. For example, you could always return find() call on the children of each node.

    If the nodes point both ways, you can easily re-trace the path up once you find the correct node.

    0 讨论(0)
  • 2020-12-17 05:55

    The following code traces the path, adding nodes to the list and removing them if they are not in the path

    boolean getPath(Node root,String targetValue,List<Integer> path)
    {
        // base case root is null so path not available
        if(root==null)
            return false;
        //add the data to the path
        path.add(root.getData());
        //if the root has data return true,path already saved
        if(root.getData().equals(targetValue))
            return true;
        //find the value in all the children
        for(Node child: children){
             if(getPath(child,targetValue,path))
              return true;
        }
        //if this node does not exist in path remove it
        path.remove(path.size()-1);
        return false;
    }
    
    0 讨论(0)
提交回复
热议问题