Adding children recursively to tree structure (children before parent) - java

I'm doing an assignment for an internship, and they gave me a task to create a navigation menu, such as this one down bellow:
. Company
.... About Us
....... Team
.... Mission
. References
.... Client 1
.... Client 2
The whole point of the task is for me to find a way to transform this input into a tree structure and then print it out recursively...
The input is:
ID NAME PARENTID
1; Company; NULL;
2; About Us; 1;
3; Mission; 1;
4; Team; 2;
5; Client1; 7;
6; Client2; 7;
7; References; NULL;
If this was a first parent then children type of input, then the task would be super easy, however I'm stuck and can't seem to understand the algorithm behind it. The whole deal is that References are added at the end, but Client 1 & Client 2 are both children of References...
Here are the codes:
Model class:
// WITH SETTERS AND GETTERS
public class NavLink
{
private String id;
private String name;
private String parentId;
private String isHidden;
private String linkUrl;
}
Triple Linked List Node Class:
public class TLLNode<NavLink>
{
public NavLink element;
public TLLNode<NavLink> parent, sibling, child;
public TLLNode(NavLink elem)
{
this.element = elem;
parent = sibling = child = null;
}
}
Tree class:
public class Tree
{
private TLLNode<NavLink> root;
public Tree(NavLink element) { this.root = new TLLNode(element); }
public TLLNode<NavLink> getRoot() { return this.root; }
public void addChild(TLLNode<NavLink> node, NavLink element)
{
TLLNode<NavLink> insert = new TLLNode<>(element);
if (node.child == null)
node.child = insert;
else
{
if (node.child.element.getName().compareTo(insert.element.getName()) > 0)
insert.sibling = node.child;
else
{
TLLNode<NavLink> tmp = node.child;
while (tmp.sibling != null)
{
if (tmp.sibling.element.getName().compareTo(insert.element.getName()) > 0)
{
insert.sibling = tmp.sibling;
break;
}
tmp = tmp.sibling;
}
tmp.sibling = insert;
}
}
insert.parent = node;
}
public void printTree() { printTreeRecursive(this.root, 0); }
private void printTreeRecursive(TLLNode<NavLink> node, int level)
{
if (node == null)
return;
for (int i=0; i < level-1; i++)
System.out.print("...");
if (node.element.getHidden().equalsIgnoreCase("False"))
System.out.println("." + node.element.getName());
TLLNode<NavLink> tmp = node.child;
while (tmp != null)
{
printTreeRecursive(tmp, level+1);
tmp = tmp.sibling;
}
}
}
And finally the Main class, where the problem is situated:
public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] parts;
List<NavLink> list = new LinkedList<>();
NavLink link = new NavLink("NULL", "/", "/", "True", "/" );
Tree tree = new Tree(link);
for (int i=0; i<n; i++)
{
parts = br.readLine().split(";");
link = new NavLink(parts[0], parts[1], parts[2], parts[3], parts[4]);
list.add(link);
}
/*TLLNode<NavLink> current;
for (NavLink item : links)
{
current = new TLLNode<>(item);
System.out.println(item);
for (NavLink tmp : links.subList(1, links.size()))
{
if (tmp.getParentId().equalsIgnoreCase(current.element.getId()))
tree.addChild(current, tmp);
}
}*/
addChildRecursive(tree, list, tree.getRoot());
tree.printTree();
}
public static void addChildRecursive(Tree tree, List<NavLink> list, TLLNode<NavLink> current)
{
if (current == null)
return;
TLLNode<NavLink> insert;
for (NavLink item : list)
{
insert = new TLLNode<>(item);
if (insert.element.getParentId() == current.element.getId())
{
tree.addChild(current, insert.element);
list.remove(insert.element);
addChildRecursive(tree, list, current.child);
}
}
}
}
The method addChildRecursive is the one that is giving me the problems, in the output it doesn't say that there are any errors.
I don't understand what needs to be done here?
P.S. Ignore the isHidden and other attributes, the main problem is with the addChildRecursive method

First of all in java it's recommended that you check if two strings are equal with now equals() function and not the == operator.
Now for your question, it's seems that you only check the child of the current node and because there could be more than one child you don't check them all.
I suggest to use a list of child or some other sort of mechanism to save all the children directly and not thru the "sibling" pointer.

Related

K-Ary Tree Implementation in Java: how to?

I've a university project about creating two classes, Tree class and Node class, to implement a k-ary tree using Java.
In the class Tree, there should be a constructor which recives as input an int that indicates the tree arity.
I've worked before with general trees and this was my result:
Class tree: *
Class node: *
I absolutely don't know where and how to start to build this project (as I don't know how to manage the arity, maybe with ArrayList?).
Any advice and suggestions will be greatly appreciated :)
Thanks in advance.
Here are the new versions of the classes, with the methods that you needed.
Node:
import java.util.ArrayList;
import java.util.List;
public class Node {
public Node parent; // The parent of the current node
public List<Node> children; // The children of the current node
public Object info;
public static int maxNrOfChildren; // Equal to the k-arity;
public Node (Object info)
{
this.info=info;
children = new ArrayList<Node>(maxNrOfChildren);
}
public void addChild(Node childNode, int position)
// You must take care so that future insertions don't override a child on i-th position
{
if(position>=maxNrOfChildren-1)
{
// Throw some error
}
else
{
System.out.println("this.children="+this.children);
if(this.children.get(position)!=null)
{
// There is alerady a child node on this position; throw some error;
}
else
{
childNode.parent=this;
this.children.set(position, childNode);
}
}
}
}
Tree:
import java.util.ArrayList;
import java.util.List;
public class Tree {
public Node root;
public Tree(int kArity)
{
Node.maxNrOfChildren=kArity;
}
public void addRoot(Object info)
{
root=new Node(info);
root.parent=null;
root.children=new ArrayList<Node>(Node.maxNrOfChildren);
}
public void addNewNodeVasithChildOfNodeU(Node u, Object info, int i)
{
Node child=new Node(info);
u.addChild(child, i);
}
// I've made the above two methods of type void, not Node, because
// I see no reason in returning anything; however, you can override by calling
//'return root;' or 'return child;'
public int numberOfNodesInTree(Node rootNode){
int count=0;
count++;
if(rootNode.children.size()!=0) {
for(Node ch : rootNode.children)
count=count+numberOfNodesInTree(ch);
}
return count;
}
public int numberOfNodesInTree()
{
return numberOfNodesInTree(this.root);
}
public void changeRoot(Node newRoot, int i)
{
Node oldRoot=this.root;
newRoot.parent=null;
newRoot.addChild(oldRoot, i);
oldRoot.parent=newRoot;
this.root=newRoot;
}
public static void main(String args[])
{
Tree tree=new Tree(3);
Node a = new Node("a");
Node b = new Node("b");
Node c = new Node("c");
tree.addRoot("root");
tree.root.addChild(a,0);
a.addChild(b,0);
tree.root.addChild(c,1);
System.out.println(tree.numberOfNodesInTree(tree.root));
}
}
The logic is correct, but I am getting some Java-related error when I run the main method and I haven't yet figured out what the problem is.
this can be a starting point:
Node Class
import java.util.ArrayList;
import java.util.List;
public class Node {
public Node parent;//the parent of the current node
public List<Node> children = new ArrayList<Node>();//the children of the current node
public String name;//or any other property that the node should contain, like 'info'
public static int maxNrOfChildren;//equal to the k-arity;
public Node (String nodeName)
{
name=nodeName;
}
public void addChild(Node childNode)
{
if(this.children.size()>=maxNrOfChildren)
{
//do nothing (just don't add another node), or throw an error
}
else
{
childNode.parent=this;
this.children.add(childNode);
}
}
}
Tree Class
import java.util.ArrayList;
import java.util.List;
public class Tree {
public Node root = new Node("root");
public Tree(int kArity)
{
Node.maxNrOfChildren=kArity;
root.parent=null;
}
public void traverseTree(Node rootNode)//depth first
{
System.out.println(rootNode.name);
if(rootNode.children.size()!=0)
for(Node ch : rootNode.children)
traverseTree(ch);
}
public static void main(String args[])
{
Tree tree=new Tree(3);
Node a = new Node("a");
Node b = new Node("b");
Node c = new Node("c");
tree.root.addChild(a);
a.addChild(b);
tree.root.addChild(c);
tree.traverseTree(tree.root);
}
}
Please give further details about your project specifications, otherwise i can't figure out which kind of functionality you need within these classes
The idea behind creating a k-array, is that this is not a conventional structure like a list or a set, the node is like an element in a linked list, it point to the n other child node and can also point to the parent, whant determine what should be the child or the parent in that sctructure is an entire different question. As for the list of child in the node you can use any structure you whant ArrayList most likely will be a good fit. The choice of a structure depend on many factors like size, how often it will be accessed does it need to be sorted etc.
Have a look at this. Hope it helps.
import java.util.ArrayList;
public class Nary
{
public static Node root;
public static int insert(Node rootNode, int parentId, ArrayList<Node> nodeToAdd)
{
if(rootNode == null)
return 0;
if(rootNode.children == null)
rootNode.children = new ArrayList<Node>();
if(rootNode.id == parentId)
{
for(int i =0; i < nodeToAdd.size(); i++)
{
Node node = nodeToAdd.get(i);
node.parent = rootNode;
rootNode.children.add(node);
}
return 1;
}
else
{
for(int i = 0; i < rootNode.children.size(); i++)
{
int resultFlag = insert(rootNode.children.get(i), parentId, nodeToAdd);
if(resultFlag == 1)
{
return 1;
}
}
}
return -1;
}
public static void traverse(Node root)
{
if(root == null)
{
return;
}
System.out.println(root.data + " " + root.id );
for(Node child : root.children)
{
traverse(child);
}
}
public static void main(String[] args) {
// Insertion
root = new Node(0, "root");
int parentId = root.id;
Node Bread = new Node(1, "Bread");
Node Milk = new Node(2, "Milk");
Node Meat = new Node(3, "Meat");
Node Eggs = new Node(4, "Eggs");
ArrayList<Node> nodeList = new ArrayList<Node>();
nodeList.add(Bread);
nodeList.add(Milk);
nodeList.add(Meat);
nodeList.add(Eggs);
insert(root, parentId, nodeList);
// Add children for Bread
parentId = Bread.id;
Node Bread0 = new Node(11, "Whole-Wheat");
Node Bread1 = new Node(12, "Whole-Grain");
Node Bread2 = new Node(13, "Italian");
ArrayList<Node> nodeList1 = new ArrayList<Node>();
nodeList1.add(Bread0);
nodeList1.add(Bread1);
nodeList1.add(Bread2);
insert(root, parentId, nodeList1);
Add children for Milk
parentId = Milk.id;
Node Milk0 = new Node(21, "Whole");
Node Milk1 = new Node(22, "skim");
Node Milk2 = new Node(23, "Almond");
ArrayList<Node> nodeList2 = new ArrayList<Node>();
nodeList2.add(Milk0);
nodeList2.add(Milk1);
nodeList2.add(Milk2);
insert(root, parentId, nodeList2);
traverse(root);
}
}
class Node{
int id;
String data;
Node parent;
ArrayList<Node> children;
public Node(int id, String data)
{
this.id = id;
this.data = data;
}
}

Printing Tree Data Structure Alphabetically

I have a big task to do as an exercise for Data Structures and algorithms, and part of it is to modify this tree data structure to print the tree in an alphabetical order.I won't post the whole task because it is huge. Im stuck on the last part which asks me to modify the given tree Data Structure to print the tree in an alphabetical order. I am stuck on it for couple of days and simple don't have any idea how to do it. Any help would be appriciated, thanks. My opinion is that i have to somehow modify the printTreeRecursive() method.
For example the current data structure will print a tree like this:
c: d c b a
(The first added child is printed last).
Where c: is the root and d c b a are his children
But im supposed to modify it to look like this:
c: a b c d
Here is the data structure:
public class SLLTree<E> implements Tree<E> {
// SLLNode is the implementation of the Node interface
class SLLNode<P> implements Node<P> {
// Holds the links to the needed nodes
SLLNode<P> parent, sibling, firstChild;
// Hold the data
P element;
public SLLNode(P o) {
element = o;
parent = sibling = firstChild = null;
}
public P getElement() {
return element;
}
public void setElement(P o) {
element = o;
}
}
protected SLLNode<E> root;
public SLLTree() {
root = null;
}
public Node<E> root() {
return root;
}
public Tree.Node<E> parent(Tree.Node<E> node) {
return ((SLLNode<E>) node).parent;
}
public int childCount(Tree.Node<E> node) {
SLLNode<E> tmp = ((SLLNode<E>) node).firstChild;
int num = 0;
while (tmp != null) {
tmp = tmp.sibling;
num++;
}
return num;
}
public void makeRoot(E elem) {
root = new SLLNode<E>(elem);
}
public Node<E> addChild(Node<E> node, E elem) {
SLLNode<E> tmp = new SLLNode<E>(elem);
SLLNode<E> curr = (SLLNode<E>) node;
tmp.sibling = curr.firstChild;
curr.firstChild = tmp;
tmp.parent = curr;
return tmp;
}
public void remove(Tree.Node<E> node) {
SLLNode<E> curr = (SLLNode<E>) node;
if (curr.parent != null) {
if (curr.parent.firstChild == curr) {
// The node is the first child of its parent
// Reconnect the parent to the next sibling
curr.parent.firstChild = curr.sibling;
} else {
// The node is not the first child of its parent
// Start from the first and search the node in the sibling list
// and remove it
SLLNode<E> tmp = curr.parent.firstChild;
while (tmp.sibling != curr) {
tmp = tmp.sibling;
}
tmp.sibling = curr.sibling;
}
} else {
root = null;
}
}
class SLLTreeIterator<T> implements Iterator<T> {
SLLNode<T> start, current;
public SLLTreeIterator(SLLNode<T> node) {
start = node;
current = node;
}
public boolean hasNext() {
return (current != null);
}
public T next() throws NoSuchElementException {
if (current != null) {
SLLNode<T> tmp = current;
current = current.sibling;
return tmp.getElement();
} else {
throw new NoSuchElementException();
}
}
public void remove() {
if (current != null) {
current = current.sibling;
}
}
}
public Iterator<E> children(Tree.Node<E> node) {
return new SLLTreeIterator<E>(((SLLNode<E>) node).firstChild);
}
void printTreeRecursive(Node<E> node, int level) {
if (node == null)
return;
int i;
SLLNode<E> tmp;
for (i = 0; i < level; i++)
System.out.print(" ");
System.out.println(node.getElement().toString());
tmp = ((SLLNode<E>) node).firstChild;
while (tmp != null) {
printTreeRecursive(tmp, level + 1);
tmp = tmp.sibling;
}
}
public void printTree() {
printTreeRecursive(root, 0);
}
public int countMaxChildren() {
return countMaxChildrenRecursive(root);
}
int countMaxChildrenRecursive(SLLNode<E> node) {
int t = childCount(node);
SLLNode<E> tmp = node.firstChild;
while (tmp != null) {
t = Math.max(t, countMaxChildrenRecursive(tmp));
tmp = tmp.sibling;
}
return t;
}
}
public interface Tree<E> {
// //////////Accessors ////////////
public Tree.Node<E> root();
public Tree.Node<E> parent(Tree.Node<E> node);
public int childCount(Tree.Node<E> node);
// //////////Transformers ////////////
public void makeRoot(E elem);
public Tree.Node<E> addChild(Tree.Node<E> node, E elem);
public void remove(Tree.Node<E> node);
// //////////Iterator ////////////
public Iterator<E> children(Tree.Node<E> node);
// //////Inner interface for tree nodes ////////
public interface Node<E> {
public E getElement();
public void setElement(E elem);
}
}
public class SLLTreeTest {
public static void main(String[] args) {
Tree.Node<String> a, b, c, d;
SLLTree<String> t = new SLLTree<String>();
t.makeRoot("C:");
a = t.addChild(t.root, "Program files");
b = t.addChild(a, "CodeBlocks");
c = t.addChild(b, "codeblocks.dll");
c = t.addChild(b, "codeblocks.exe");
b = t.addChild(a, "Nodepad++");
c = t.addChild(b, "langs.xml");
d = c;
c = t.addChild(b, "readme.txt");
c = t.addChild(b, "notepad++.exe");
a = t.addChild(t.root, "Users");
b = t.addChild(a, "Darko");
c = t.addChild(b, "Desktop");
c = t.addChild(b, "Downloads");
c = t.addChild(b, "My Documents");
c = t.addChild(b, "My Pictures");
b = t.addChild(a, "Public");
a = t.addChild(t.root, "Windows");
b = t.addChild(a, "Media");
t.printTree();
t.remove(d);
t.printTree();
System.out.println("The maximum number of children is "
+ t.countMaxChildren());
}
}
As I see, my initial suggestion is good-enough for the asker and other commenters as well. So, as this is a studying task, I will not write code as an answer (I would take all the fun, wouldn't I?). I will share some important checkpoints to reach in the thought process, which, if reached should lead to the solution:
we need a Collection
we need to use a breadth-first traversing (printTreeRecursive is a good example)
we need to look at the while cycle of printTreeRecursive, as it is key to reach a traversing
whenever we reach a node, we should insert sort the node into the collection
after the traversing, we iterate the Collection and print out its elements

Add nodes in linked list

Trying to implement single-linked-list in below program, i am really not able to undertsand how to add a node in an Linked list (for start, m trying it on empty linked list).
To put it plain simple,i tried to setData and setNext but getSizeofList() return 0 everytime....its really looking like a rocket science to me now!!
Question : Can some-one tell me how to implement it....or rather, add a node to existing linked list....
What i have tried so far and why they dint worked out: i referenced multiple programs but they were too complex for me to understand(rocket science), so wrote below program from what i understood from algorithms....but even in algo's, they just show methods on how to implement and this is where i failed, as, i dont understand,what data-type and value is to be passed for adding a node...
please not that m not a java guy, so please go easy, this question comes in as an attempt to learn
package Data_S;
public class Linked_List {
private int data;
private Linked_List next_ptr;
private Linked_List headNode = null;
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Linked_List ll = new Linked_List();
//ll.setnext(25);
ll.insert_node(24);
ll.traverse();
ll.getSizeofList();
}
//size of list
public void getSizeofList()
{
int l = 0;
Linked_List curr = headNode;
while(curr != null)
{
l++;
curr = curr.getnext();
}
System.out.print("Size of list is = "+l);
}
//insert node
public void insert_node(/*Linked_List node, */int data)
{
if(headNode == null)
{
System.out.println("in insert"); // checking
this.setnext(headNode);
this.setData(data);
System.out.print("value = "+this.getData());
}
}
//set data for this node
public void setData(int data)
{
this.data = data;
}
//return the data
public int getData()
{
return this.data;
}
//set next pointer
public void setnext(Linked_List next_ptr)
{
this.next_ptr = next_ptr;
}
//get next pointer
public Linked_List getnext()
{
return this.next_ptr;
}
}
You have to make a distinction between the single chains (Node) of a linked list, and the entire container (LinkedList).
public class LinkedList {
Node head;
int size; // Maybe
public void insertAtEnd(int data) {
Node previous = null;
for (Node current = head; current != null; current = current.next) {
previous = current;
}
Node baby = new Node(data);
if (previous == null) {
head = baby;
} else {
previous.next = baby;
}
++size;
}
public void insertInSortedList(int data) {
Node previous = null;
Node current = null;
for (current = head; current != null && data < current.data;
current = current.next) {
previous = current;
}
Node baby = new Node(data);
baby.next = current;
if (previous == null) {
head = baby;
} else {
previous.next = baby;
}
++size;
}
}
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
One may sometimes see encapsulation as:
public class LinkedList {
private static class Node {
}
...
}
You never set headnode. In insertnode you just use setnext which does not set headnode. You are mixing the top class and the node implementation together.
Here is an example of how to implement a linked list in java for further reference:
How do I create a Linked List Data Structure in Java?

How to build a link list in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I implement a Linked List in Java?
We know there is no pointers in java. Then what is the best way to build the link list in java?
The best way is to not build it. Java already has a LinkedList class amongst its rather large selection of collection classes.
You would be better off using what the language/library already provides.
You have an object that essentially contains two variables, no methods (bare minimum; however, you could have methods if you wanted). Something like:
class Link
{
int data;
Link next;
}
Then you create a new Link like any other object. Set the data to the data you want a node to hold. Then set the Link node to the node that it will be "pointing" to (or null if it doesn't point to another one).
Note: you can also have a previous node (which points to the previous node) if need be.
try having this code.
public class Main {
public static void main(String[] args) {
LinkedList theList = new LinkedList();
LinkedListIterator theItr;
theItr = theList.zeroth();
printList(theList);
for (int i = 0; i < 10; i++) {
theList.insert(new Integer(i), theItr);
printList(theList);
theItr.advance();
}
System.out.println("Size was: " + listSize(theList));
}
public static int listSize(LinkedList theList) {
LinkedListIterator itr;
int size = 0;
for (itr = theList.first(); itr.isValid(); itr.advance())
size++;
return size;
}
public static void printList(LinkedList theList) {
if (theList.isEmpty())
System.out.print("Empty list");
else {
LinkedListIterator itr = theList.first();
for (; itr.isValid(); itr.advance())
System.out.print(itr.retrieve() + " ");
}
System.out.println();
}
}
class LinkedList {
public LinkedList() {
header = new ListNode(null);
}
public boolean isEmpty() {
return header.next == null;
}
public void makeEmpty() {
header.next = null;
}
public LinkedListIterator zeroth() {
return new LinkedListIterator(header);
}
public LinkedListIterator first() {
return new LinkedListIterator(header.next);
}
public void insert(Object x, LinkedListIterator p) {
if (p != null && p.current != null)
p.current.next = new ListNode(x, p.current.next);
}
public LinkedListIterator find(Object x) {
ListNode itr = header.next;
while (itr != null && !itr.element.equals(x))
itr = itr.next;
return new LinkedListIterator(itr);
}
public LinkedListIterator findPrevious(Object x) {
ListNode itr = header;
while (itr.next != null && !itr.next.element.equals(x))
itr = itr.next;
return new LinkedListIterator(itr);
}
public void remove(Object x) {
LinkedListIterator p = findPrevious(x);
if (p.current.next != null)
p.current.next = p.current.next.next; // Bypass deleted node
}
private ListNode header;
}
class LinkedListIterator {
LinkedListIterator(ListNode theNode) {
current = theNode;
}
public boolean isValid() {
return current != null;
}
public Object retrieve() {
return isValid() ? current.element : null;
}
public void advance() {
if (isValid())
current = current.next;
}
ListNode current;
}
class ListNode {
public ListNode(Object theElement) {
this(theElement, null);
}
public ListNode(Object theElement, ListNode n) {
element = theElement;
next = n;
}
public Object element;
public ListNode next;
}

Construct a tree structure from list of string paths

I have a collection of string paths like ["x1/x2/x3","x1/x2/x4","x1/x5"] in a list.
I need to construct a tree-like structure from this list which can be iterated to get a pretty printed tree.
like this
x1
/ \
x5 x2
/ \
x3 x4
Any ideas/suggestions?
I believe that the problem can be attacked first by processing the list of strings EDIT: The correct answer chosen was an elegant implementation, other suggestions were good too.
Follow an implementation of naive implementation of a visitable tree:
class Tree<T> implements Visitable<T> {
// NB: LinkedHashSet preserves insertion order
private final Set<Tree> children = new LinkedHashSet<Tree>();
private final T data;
Tree(T data) {
this.data = data;
}
void accept(Visitor<T> visitor) {
visitor.visitData(this, data);
for (Tree child : children) {
Visitor<T> childVisitor = visitor.visitTree(child);
child.accept(childVisitor);
}
}
Tree child(T data) {
for (Tree child: children ) {
if (child.data.equals(data)) {
return child;
}
}
return child(new Tree(data));
}
Tree child(Tree<T> child) {
children.add(child);
return child;
}
}
interfaces for Visitor Pattern:
interface Visitor<T> {
Visitor<T> visitTree(Tree<T> tree);
void visitData(Tree<T> parent, T data);
}
interface Visitable<T> {
void accept(Visitor<T> visitor);
}
sample implementation for Visitor Pattern:
class PrintIndentedVisitor implements Visitor<String> {
private final int indent;
PrintIndentedVisitor(int indent) {
this.indent = indent;
}
Visitor<String> visitTree(Tree<String> tree) {
return new IndentVisitor(indent + 2);
}
void visitData(Tree<String> parent, String data) {
for (int i = 0; i < indent; i++) { // TODO: naive implementation
System.out.print(" ");
}
System.out.println(data);
}
}
and finally (!!!) a simple test case:
Tree<String> forest = new Tree<String>("forest");
Tree<String> current = forest;
for (String tree : Arrays.asList("x1/x2/x3", "x1/x2/x4", "x1/x5")) {
Tree<String> root = current;
for (String data : tree.split("/")) {
current = current.child(data);
}
current = root;
}
forest.accept(new PrintIndentedVisitor(0));
output:
forest
x1
x2
x3
x4
x5
Just split each path by its delimiter and then add them to a tree structure one by one.
i.e. if 'x1' does not exist create this node, if it does exist go to it and check if there is a child 'x2' and so on...
I'd make the tree one string at a time.
Make an empty tree (which has a root node - I assume there could be a path like "x7/x8/x9").
Take the first string, add x1 to the root node, then x2 to x1, then x3 to x2.
Take the second string, see that x1 and x2 are already there, add x4 to x2.
Do this for every path you have.
Create an Object Node which contains a parent (Node) and a List of children (Node).
First split the string using ",". For every splitted string you split the string using "/".
Search for the first node identifier (e.g x1) in the root list.
If you can find it, use the node to find the next node identifier (e.g. x2).
If you can not find a node, add the node to the last node you was able to find in the existing lists.
After you have created the list structure, you can print the list to the screen. I would make it recursive.
NOT TESTED, just an animation
public void print(List nodes, int deep) {
if (nodes == null || nodes.isEmpty()) {
return;
}
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < deep; i++) {
buffer.append("---");
}
for (Iterator iterator = nodes.iterator(); iterator.hasNext();) {
Node node = (Node)iterator.next();
System.out.println(buffer.toString() + " " + node.getIdentifier());
print(node.getChildren(), deep + 1);
}
}
public class Menu {
private String path;
private List<Menu> children;
public Menu(String path) {
this.path = path;
children = new ArrayList<>();
}
public void addChild(Menu child) {
children.add(child);
}
public List<Menu> getChildren() {
return children;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Menu getChild(String data) {
for (Menu n : children)
if (n.path.equals(data)) {return n;}
return null;
}
}
Tree builder class:
public class MenuTree {
private Menu root;
public MenuTree() {
root = new Menu("");
}
public void add(String str) {
Menu current = root;
StringTokenizer s = new StringTokenizer(str, "/");
while (s.hasMoreElements()) {
str = (String) s.nextElement();
Menu child = current.getChild(str);
if (child == null) {
current.addChild(new Menu(str));
child = current.getChild(str);
}
current = child;
}
}
public JSONObject toJSON() {
try {
return new JSONObject(new ObjectMapper().writeValueAsString(this.root));
} catch (JsonProcessingException e) {
return null;
}
}
}
Usage:
String slist[] = new String[]{
"mnt/sdcard/folder1/a/b/file1.file",
"mnt/sdcard/folder1/a/b/file2.file",
"D/a/b/c.file",
};
MenuTree t = new MenuTree();
for (String s : slist) {
t.add(s);
}
System.out.println(t.toJSON().toString());
JSONObject result:
{"path":"","children":[{"path":"mnt","children":[{"path":"sdcard","children":[{"path":"folder1","children":[{"path":"a","children":[{"path":"b","children":[{"path":"file1.file","children":[]},{"path":"file2.file","children":[]}]}]}]}]}]},{"path":"D","children":[{"path":"a","children":[{"path":"b","children":[{"path":"c.file","children":[]}]}]}]}]}
Make your tree for every string in array.
Just split path for '/' , check whether the node exists in your tree or not, if it exists then move on... otherwise create a new node and add this node in childrens of parent node.
Iterate using recursion.
Following is model for tree's node.
Class Node{
string name;
List<Node> childrens;
Node(string name){
this.name = name;
this.childrens = new List<Node>();
}
}
This is way how I am doing tree from path (folders) structure. Maybe should help someone with basic logic.
Node:
public class Node {
private String path;
private List<Node> children;
public Node(String path) {
this.path = path;
children = new ArrayList<>();
}
public String getName() {
return getName(path);
}
private String getName(String path) {
String[] split = path.split("\\\\");
return split[split.length - 1];
}
public void addChild(Node child) {
children.add(child);
}
public List<Node> getChildren() {
return children;
}
public String getPath() {
return path;
}
}
FilesTree:
public class FilesTree {
private static final Logger log = Logger.getLogger(FilesTree.class.getName());
private FilesTree() {}
private static void createTree(Node root, List<String> paths) {
for (String path : paths) {
addNode(root, Arrays.asList(path.split("\\\\")), "");
}
}
private static void addNode(Node node, List<String> path, String nodePath) {
if (!path.isEmpty()) {
nodePath = nodePath.equals("") ? path.get(0) : String.format("%s\\%s", nodePath, path.get(0));
}
if (node.getChildren().isEmpty() && path.size() == 1) {
node.addChild(new Node(nodePath));
} else if (!node.getChildren().isEmpty()) {
for (Node actual : node.getChildren()) {
if (actual.getName().equals(path.get(0))) {
addNode(actual, path.subList(1, path.size()), nodePath);
return;
}
}
node.addChild(new Node(nodePath));
} else {
log.info("Without children but with size: " + path.size());
}
}
}

Categories