我试图提高我对学习实现算法的把握,所以我开始尝试在java中实现深度优先搜索。但是,我无法找到创建Node类并使用它创建树结构的正确方法。你能帮我找一个更好的方法吗?
节点类
public class Node<T>{
T data;
Node<T> parent;
ArrayList<Node<T>> children;
public Node(T data)
{
this.data = data;
this.children = new ArrayList<Node<T>>();
}
public Node<T> addChild(T child)
{
Node<T> childNode = new Node<T>(child);
childNode.parent = this;
this.children.add(childNode);
return childNode;
}
public ArrayList<Node<T>> removeChild(T child)
{
Node<T> childNode = new Node<T>(child);
ArrayList<Node<T>> children = this.children;
children.remove(child);
return children;
}
}
DepthFirstSearchClass
public class DepthFirstSearch<T>{
public Node<T> root;
public Node<T> goal;
public Hashtable<Node<T>, Boolean> visited;
public boolean DepthFirstSearch(Node<T> root, Node<T> goal)
{
this.root = root;
this.goal = goal;
if(this.root == this.goal)
{
System.out.println("The goal has been reached.");
return true;
} else {
if(root.children.size()-1 >0)
{
for(Node<T>child: root.children)
{
DepthFirstSearch(child, goal);
}
}
return false;
}
}
}
主要
public class Main{
public static Node<String> rootNode;
public static Node<String> childOne;
public static Node<String> childTwo;
public static Node<String> childThree;
public static DepthFirstSearch dfs;
public static void main(String [] args)
{
//initializing variables
rootNode = new Node<String>("rootNode");
childOne = new Node<String>("childOne");
childTwo = new Node<String>("childTwo");
childThree = new Node<String>("childThree");
dfs = new DepthFirstSearch();
//building the trees
rootNode.addChild(childOne);
rootNode.addChild(childThree);
childOne.addChild(childTwo);
dfs.DepthFirstSearch(rootNode, childTwo);
}
}
答案 0 :(得分:0)
从代码中删除以下行:
if(root.children.size()-1 >0)
。
首先,如果给定节点没有子节点,则阻止访问单个子节点,其次for(Node<T>child: root.children)
将跳过迭代。
除此之外,你的DFS看起来不错。