I am trying to build a tree and I would like to link parent nodes to children based on a filepath like structure such as the one below, where The World is the root:
The World
The World/Asia
The World/Asia/Afghanistan
The World/Asia/Iran
The World/Asia/China";
I want to turn it into this:
The approach I am taking is as follows. I am wondering if someone could give me a hand in pointing me in the right direction. I am not sure if my logic is correct?
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);
}
}
}
Hope the below code helps you in creating your folder structure using 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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With