2012-10-26 3 views
0

다음과 같은 문자열 값 목록이 있습니다 ... A, A_AChild, A_AChild_furtherChild, A_BChild, A_CChild 등. 'UnderScore'로 구분 된 값은 A가 부모 AChild임을 나타냅니다. 자식 및 AChild는 furtherChild의 부모입니다. similary BChild와 CChild의 부모는 A.입니다. 표현을 위해 구조와 같은 트리를 생성해야합니다.Java에서 고유 코드 목록으로 트리 구조 만들기

A 
AChild 
    furtherChild 
BChild 
Child 

어떻게하면됩니까? 모든 알고리즘이나 자바 프로그램은 매우 높이 평가 될 것이다.

+0

어떤 접근 방법을 생각해 봤어? –

+0

가장 일반적인 방법으로 생각하는 것조차 생각조차 할 수 없었습니다. :-( –

+0

유휴 상태의 두뇌에 약간의 압박감을 가하고 작동시켜야합니다. 그리고 몇 가지 접근법을 생각해보십시오. 그러면 누군가가 당신을 도울 수 있습니다. –

답변

0

먼저 노드와 트리 데이터 구조를 만듭니다.

Node: 
Node(String value) 


Tree 
Tree(Node node) : Creates a tree with root as node 

Node getNode(Node node, String nodeToRetrive) nodeToRetrive will be a child of node 
returns null if not found 

Node addNode(Node node, String nodeToBeAdded) nodeToBeAdded will be added as a new child of node and the newly added Node would be returned 

는 A.

Node root=new Node("A"); 
Tree tree=new Tree(root); 

분할 "_"에서 토큰에 입력 문자열로 루트로 트리를 만듭니다. 예를 들어, "A_AChild_furtherChild"는 "A", "AChild", "furtherChild"로 나뉩니다.

String s="A_AChild_furtherChild"; 
String[] tokens=s.split("_"); 

두 번째부터 시작하는 토큰 (이 경우 "아동")을 반복하고 필요한 처리를 수행합니다.

Node node=tree.root; Node n; 
for(i=1 ;i <tokens.length; i++){ 
    n=getNode(node,tokens[i]); 
    if(n==null){ 
    n=addNode(node,tokens[i]); 
    } 
    node=n; 
} 

위의 루프를 사용하여 전체 트리를 구성 할 수 있습니다.

트리의 노드 값을 재귀 적으로 검색하십시오.

public void printTree(Node n, int level){ 
    display level number of spaces and print the value held by Node n. 
    for(each of the children of n){ 
    printTree(theChild, level+1) 
    } 
} 

위의 재귀 적 방법은 처음에 다음과 같은 방법으로 호출 할 수 있습니다 :

printTree(root,0); 
+0

감사합니다. –

0

내가 내 자신에이 문제를 해결 ..

:-)이 코드입니다. 나는 그것이 효율적이지 않을지도 모른다 :

Set<String> treeSet = new TreeSet<String>(); 
     treeSet.add("FEES"); 
     treeSet.add("FEES_NUSF"); 
     treeSet.add("FEES_NUSF_NUS1"); 
     treeSet.add("EXPE"); 
     treeSet.add("EXPE_NUSE"); 

     for (String string : treeSet) { 


      int splitSize = string.split("_").length; 

      if(splitSize > 1){ 
       //log("In if : "+splitSize); 
       StringBuilder sb = new StringBuilder(""); 
       for (int i = 0; i < splitSize; i++) { 
        sb.append(" "); 
       } 
       sb.append(string); 
       print(sb.toString()); 
      } 
      else{ 
       print(string); 
      } 
     }