aud*_*tic 4 java tree tree-traversal data-structures
我正在尝试构建一个树,我想基于类似于下面的文件路径将父节点链接到子节点,其中世界是根:
The World
The World/Asia
The World/Asia/Afghanistan
The World/Asia/Iran
The World/Asia/China";
Run Code Online (Sandbox Code Playgroud)
我想把它变成这个:

我采取的方法如下.我想知道是否有人能帮助我指出正确的方向.我不确定我的逻辑是否正确?
public void linkNodeToParent(String path, Node n)
{
String[] pathNodes = path.split("/");
Node parent = root;
for(int i = 0; i < pathNodes.length; ++i)
{
for(int j = 0; j < parent.getChildren().size(); ++j)
{
if(parent.getChildren().get(j).getNodeName().equals(pathNodes[i]))
parent = parent.getChildren().get(j);
}
}
}
Run Code Online (Sandbox Code Playgroud)
希望以下代码可以帮助您使用Tree创建文件夹结构
import java.util.*;
class Tree
{
class Node
{
String data;
ArrayList<Node> children;
public Node(String data)
{
this.data = data;
children = new ArrayList<Node>();
}
public Node getChild(String data)
{
for(Node n : children)
if(n.data.equals(data))
return n;
return null;
}
}
private Node root;
public Tree()
{
root = new Node("");
}
public boolean isEmpty()
{
return root==null;
}
public void add(String str)
{
Node current = root;
StringTokenizer s = new StringTokenizer(str, "/");
while(s.hasMoreElements())
{
str = (String)s.nextElement();
Node child = current.getChild(str);
if(child==null)
{
current.children.add(new Node(str));
child = current.getChild(str);
}
current = child;
}
}
public void print()
{
print(this.root);
}
private void print(Node n)
{
if(n==null)
return;
for(Node c : n.children)
{
System.out.print(c.data + " ");
print(c);
}
}
public static void main(String[] args)
{
Tree t = new Tree();
t.add("The World");
t.add("The World/Asia");
t.add("The World/Asia/Afghanistan");
t.add("The World/Asia/Iran");
t.add("The World/Asia/China"); // Even if you insert only this statement.
// You get the desired output,
// As any string not found is inserted
t.print();
}
}
Run Code Online (Sandbox Code Playgroud)