2013-05-15 1 views
3

Я пытаюсь построить дерево, и я хотел бы связать родительские узлы с детьми на основе FilePath как структуры, такие, как показано ниже, где Мир является корнем:Создайте дерево из пути к файлу, правильно ли моя логика?

The World 
    The World/Asia 
    The World/Asia/Afghanistan 
    The World/Asia/Iran 
    The World/Asia/China"; 

Я хочу, чтобы превратить его в этом: enter image description here

Подход, который я принимаю, заключается в следующем. Мне интересно, может ли кто-нибудь дать мне руку, указывая на меня в правильном направлении. Я не уверен, правильна ли моя логика?

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

} 
+0

В чем проблема? Какой у Вас вопрос? –

+0

Я не уверен, если я правильно его реализую, если моя логика правильная – audiFanatic

+0

** «Правильно ли моя логика?» ** * * * вопрос. Если это ваш вопрос, напишите [edit] (http://stackoverflow.com/posts/16560509/edit) в вопрос! –

ответ

0

Если добавить один люфт «/» на каждом конце, как мы говорили в чате, то эта программа будет работать

void split() 
    { 
     String path= 
       "The World/"+ 
       "The World/Asia/"+ 
       "The World/Asia/Afghanistan/"+ 
       "The World/Asia/Iran/"+ 
       "The World/Asia/China/"; 
     String[] pathNodes = path.split("/"); 

//  for(String s:pathNodes) 
//  { 
//   System.out.println(s); 
//  } 

     String root="The World"; 
     String continent="Asia"; 
     List<String> ls=new ArrayList<String>(); 

     for(int i=0;i<pathNodes.length;i++) 
     { 
      if(pathNodes[i].equals(root)) 
      { 
       if(pathNodes[i+1].equals(continent)) 
       { 
        ls.add(pathNodes[i+2]); 
       } 
      } 
     } 
     for(String s:ls) 
     { 
      System.out.println(s); 
     } 
    } 
5

Надежда ниже код поможет вам в создании структуры папок с использованием дерева

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(); 
    } 
} 
  1. «добавить» метод принимает папку или весь путь в качестве входных данных и хранит I t в дереве, как вам нужно. Он берет первую строку и проверяет, если она уже присутствует в дереве, но она добавляет ее и переходит к следующей строке (папке на ваших условиях).
  2. Метод печати поможет вам проверить хранение данных в дереве.

 Смежные вопросы

  • Нет связанных вопросов^_^