java - Build a Tree Out of File Path, Is My Logic Correct? -
i trying build tree , link parent nodes children based on filepath structure such 1 below, world root:
world world/asia world/asia/afghanistan world/asia/iran world/asia/china"; i want turn this: 
the approach taking follows. wondering if give me hand in pointing me in right direction. not sure if logic correct?
public void linknodetoparent(string path, node n) { string[] pathnodes = path.split("/"); node parent = root; for(int = 0; < 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 below code helps in creating 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"); // if insert statement. // desired output, // string not found inserted t.print(); } } - the "add" method takes folder or entire path input , stores in tree required. takes first string , checks if it's present in tree other wise adds , proceed next string (folder in terms).
- the print method verify storage of data in tree.
Comments
Post a Comment