Construct a tree structure from list of string paths - java

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());
}
}
}

Related

my linked list is returning just last entered node

I'm doing a dictionary system for my school assignment. The idea that I'm trying to do is to store every single word and its definitions in a node and searching them using a binary search tree.
But there has an issue that occurred. When I add a word and definition in a node in the linked list, the wordList() method returns the last node that I've entered. I think I am having trouble implementing and linking the nodes. Could you please help me? (Note: Vocab is my test class)
public class Node {
private static String word;
private static String definition;
private Node link;
public Node() {
link = null;
word = null;
}
public Node(String newWord) {
setWord(newWord);
link = null;
}
public Node(String newWord, Node linkValue) {
setWord(newWord);
link = linkValue;
}
public Node(String newWord, String newDefinition, Node linkValue) {
setWord(newWord, newDefinition);
link = linkValue;
}
public Node(String newWord, String newDefinition) {
setWord(newWord, newDefinition);
}
#Override
public String toString() {
return "Node [word=" + word + ", link=" + link + "]";
}
public static String getDefinition() {
return definition;
}
public void setDefinition(String definition) {
this.definition = definition;
}
public static String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public void setWord(String word, String definition) {
this.word = word;
this.definition = definition;
}
public Node getLink() {
return link;
}
public void setLink(Node link) {
this.link = link;
}
}
public class LinkedList {
protected static Node first;
private Node last;
public LinkedList() {
super();
this.first = null;
this.last = null;
}
public LinkedList(String wordName, String wordDefinition, Node first2) {
// TODO Auto-generated constructor stub
}
public boolean isEmpty() {
return(first == null);
}
public void insert(String newWord, String newDefinition) {
if(isEmpty()) {
first= last= new Node(newWord, newDefinition, first);
}
else {
first = new Node(newWord, newDefinition, first);
}
}
public void wordList() {
Node current = first;
while(current != null) {
System.out.println(current.getWord());
current = current.getLink();
}
}
public static Node getFirst() {
return first;
}
public void setFirst(Node first) {
this.first = first;
}
public Node getLast() {
return last;
}
public void setLast(Node last) {
this.last = last;
}
}
public class Vocab {
public static void main(String[] args) {
LinkedList dictionary = new LinkedList();
Node a = new Node("Assembly","A unit of fitted parts that naje yo a mechanism or machine, such as the headstock assemble of a lathe.");
dictionary.setFirst(a);
Node b = new Node("Boil","Agitation of a bath of metal caused by the liberation of a gas beneath its surface.");
a.setLink(b);
b.setLink(null);
dictionary.wordList();
}
}
If you want to use your LinkedList, use its methods rather than making the manipulations by hand:
LinkedList dictionary = new LinkedList();
// Node a = new Node("Assembly","A unit of fitted parts that naje yo a mechanism or machine, such as the headstock assemble of a lathe.");
dictionary.setFirst(a);
//Node b = new Node("Boil","Agitation of a bath of metal caused by the liberation of a gas beneath its surface.");
//a.setLink(b);
//b.setLink(null);
dictionary.wordList();
In the code above I have commented out all lines of code that go one level too deep. On the usage side you should never care that the Node class is used internally.
Have a look at LinkedList methods that will work for you. Then try to think of why when you are not using them you never alter the internal properties of the list, thus leaving it broken an half setup.
EDIT: By the way consider removing the setFirst and setLast methods that accept Node instances. They are only confusing you and should have never been there.

Adding children recursively to tree structure (children before parent)

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.

Use the set method directly or loop over the arrayList to set the data

Can someone explain me why the childern node of the nextNode are deleted after clearing the cache.clear(); if I set the the cache conetent arrayList by invoking:
child1.setNext(cache);
and they are not being deleted if I adding them with the for loop child1.next.add(cacheNode);
for (TrieNode cacheNode : cache) {
child1.next.add(cacheNode);
}
The work below works but I just want to understand Why can not I use child1.setNext(cache);?
Code:
ArrayList<TrieNode> cache = new ArrayList<TrieNode>();
if (nextNode.getNext() != null
&& !nextNode.getNext().isEmpty()) {
for (TrieNode nextNodeChildern : nextNode.getNext()) {
cache.add(nextNodeChildern);
}
nextNode.setEdge(communsubString);
nextNode.getNext().clear();
TrieNode child1 = new TrieNode(substringSplit1);
//child1.setNext(cache);
for (TrieNode cacheNode : cache) {
child1.next.add(cacheNode);
}
nextNode.next.add(child1);
cache.clear();
TrieNode child2 = new TrieNode(substringSplit2);
child2.setWord(true);
nextNode.next.add(child2);
}
TrieNode class:
class TrieNode {
ArrayList<TrieNode> next = new ArrayList<TrieNode>();
String edge;
boolean isWord;
// To create normal node.
TrieNode(String edge) {
this.edge = edge;
}
// To create the root node.
TrieNode() {
this.edge = "";
}
public ArrayList<TrieNode> getNext() {
return next;
}
public void setNext(ArrayList<TrieNode> next) {
this.next = next;
}
public String getEdge() {
return edge;
}
public void setEdge(String edge) {
this.edge = edge;
}
public boolean isWord() {
return isWord;
}
public void setWord(boolean isWord) {
this.isWord = isWord;
}
}
When you pass cache to setNext you're passing a reference to the cache list, i.e. the List in your node and the List in your main code points to the same List in memory. When you call clear you're emptying out that list, which is being used by your node.
You need to use a copy of the list for your node by either taking a copy outside or inside the node class, so something like this would work:
public void setNext(ArrayList<TrieNode> next) {
this.next = new ArrayList<>(next);
}
This will create a new ArrayList inside the node and copy all the elements from next into it.

How to print first child - sibling structure

I am trying to figure out how to print a first-child next sibling tree. What I want is the following:
root
|
firstChild - sibling - sibling
|
child - sibling - sibling
I have the following code to add childs and siblings :
class Program
{
static void Main(string[] args)
{
GeneralTree<string> tree = new GeneralTree<string>();
tree.root = new TreeNode<string>
{
Data = "Root"
};
TreeNode<string> child = tree.addChild(tree.root, "Child");
tree.addSibling(child, "Sibling");
tree.print(tree.root);
}
}
class GeneralTree<T>
{
public TreeNode<T> root;
public TreeNode<T> addChild(TreeNode<T> parent, T data)
{
parent.FirstChild = new TreeNode<T>
{
Data = data,
NextSibling = parent.FirstChild
};
return parent.FirstChild;
}
public TreeNode<T> addSibling(TreeNode<T> sibling, T data)
{
sibling.NextSibling = new TreeNode<T>
{
Data = data,
FirstChild = sibling.NextSibling
};
return sibling.NextSibling;
}
int count = 0;
public void print(TreeNode<T> Node)
{
if(Node !=null)
{
Console.WriteLine(Node.Data);
print(Node.FirstChild);
++count;
Console.WriteLine(count);
print(Node.NextSibling);
}
}
}
class TreeNode<T>
{
public T Data { get; set; }
public TreeNode<T> FirstChild { get; set; }
public TreeNode<T> NextSibling { get; set; }
}
Does anyone now how to print that out?
Thanks in advance!
I choosed to merge TreeNode and GeneralTree in this way :
public class TreeNode<T>
{
public T data;
public List<TreeNode<T>> childs;
public TreeNode<T> firstChild()
{return childs.get(0);}
public void appendChild(TreeNode<T> child)
{childs.add(child);}
public void print() {/* ... */}
/* ... */
public static void main(String args[])
{ /* ... */}
}
Then, a way to write print() recursively :
public void print()
{
print(0);
}
public void print(int offset)
{
if (node == null) return; // nothing to print anymore
System.out.println(this.data); // printing the root data
TreeNode<T> lastChild=null;
String output = "";
for(Iterator<TreeNode<T>> i = childs.iterator(); i.hasNext(); )
{
lastChild = i.next();
if (output != "") output += " - ";
output += lastChild.data;
}
// length will be the next line offset
// (size of the current line output minus last item length
int length = output.length()-lastChild.toString().length;
// use a repeat() string function like this one :
output = org.apache.commons.lang.StringUtils.repeat(" ", length) + (length>0?"|":"") + output;
System.out.println (output);
lastChild.print(length);
}
}
Unfortunately I can't validate my code right now, If you have issues, please let me know.

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;
}
}

Categories