2016-10-23 9 views
1

왼쪽 노드에 오른쪽 노드를 추가하는 데 문제가있는 것 같습니다. 내가있을 것 같다 내 노드가 성공적으로 생성된다고 가정선주문 순회 트리

public class Node { 
    public String name; 
    public int year; 
    //this will help with determining the parent in the insertion process 
    public int children;  
    public Node parent; 
    public Node left; 
    public Node right; 


    public Node(String name, int year, int children){ 
     this.name = name; 
     this.year = year; 
     this.children = children; 
    } 
} 

: 나는 사전 순으로 나열되어있는 입력 파일 (.txt입니다) 여기

Fred 1900 
2 
John 1925 
3 
Mary 1950 
2 
Jason 1972 
0 
Heather 1975 
2 
Sydney 2002 
0 
Hailey 2005 
0 
John 1951 
1 
Amy 1983 
0 
Fred 1953 
3 
Mark 1977 
0 
Sarah 1979 
1 
Michael 2005 
0 
Adam 1982 
0 
Joan 1927 
2 
Susan 1949 
0 
David 1952 
1 
Fred 1980 
0 

내 노드 클래스가 실제 나무를 만드는 문제.

public class FamilyTree {  

    public Node familyTree; 

    private Node pivotalNode; 
    private Node parent; 
    private int children = 0; 
    //This method adds a family member to the family tree  
    public void add(Node newNode){ 
     familyTree = add(familyTree,newNode); 
    } 
    private Node add(Node familyTree, Node newNode){   
     if(familyTree == null){ 
      children = newNode.children; 
      newNode.parent = parent; 
      familyTree = newNode; 

     } 
     else if(children > 0){ 
      parent = familyTree; 
      familyTree.left = add(familyTree.left, newNode); 
      pivotalNode = familyTree.left; 
     } 
     else if(children == 0){   

      familyTree.right = add(familyTree.right, newNode); 
      return pivotalNode; 
     }   
     return familyTree; 
    } 
} 

결과는 다음과 같이 트리를 보여주고 있습니다 :

public class Operations { 

    //Not necessary but it helps me to get more organized. Just want to extract information first. 
    public static ArrayList<String> information = new ArrayList<String>(); 

    public static void main(String args[]){ 
     //extract information from file 
     getFileContents(); 

     //Object initialization 
     FamilyTree family = new FamilyTree(); 

     //some useful variables for loop below 
     int children =0; 
     String[] splitted = null; 
     Node member = null;   

     for(int i=0; i<information.size(); i++){ 
      //Every other line in the text file perform a different operation 
      if(i % 2 == 1){ 
       try{ 
        children = Integer.parseInt(information.get(i)); 
        member = new Node(splitted[0], Integer.parseInt(splitted[1]), children); 
        family.add(member); 
       } 
       catch(Exception e){ 
        //this determines if the pattern is broken 
        break; 
       } 
      } 
      if(i % 2 == 0){        
       splitted = information.get(i).split("\\s+"); 
       //this determines a pattern difference     
       if(splitted.length < 2){ 
        break; 
       } 
      } 
     } 
     System.out.print("hi"); 
    } 
    //Pretty self explanatory. Read each line of the file and store it into an array. 
    //Not necessary as everything could technically be done at once (insertion), but this keeps me 
    //more organized to put everything together later on 
    public static void getFileContents(){ 
     try{ 
      BufferedReader br = new BufferedReader(new FileReader("includes\\assn2in.txt"));    

      String line; 
      String info; 

      while ((line = br.readLine()) != null) { 
       info = line.replaceAll("\\s+", " "); 
       information.add(info);    
      }    
      br.close(); 


     } 
     catch(IOException e){ 
      System.out.println("Error: "+e); 
     } 
    } 
} 

어떤 도움을 주시면 감사하겠습니다 감사 : enter image description here

여기 내 주요 방법이다. 즉, 아이들을 대표하는 leftright 구성원이 포함 - - 당신이

답변

0

하나의 큰 문제는 Node 클래스 모델 이진 트리 구조가 있다는 것입니다하지만 데이터 자체가이 구조에 적합하지 않습니다. 다이어그램을 보면 일부 노드에 세 개의 자녀가 있다는 것을 알 수 있습니다 (예 : John 1925 및 Fred 1953).

public class Node { 
    public String name; 
    public int year; 
    //this will help with determining the parent in the insertion process 
    public int expectedNumberOfChildren;  
    public Node parent; 
    public ArrayList<Node> children; 

    public Node(String name, int year, int expectedNumberOfChildren){ 
     this.name = name; 
     this.year = year; 
     this.expectedNumberOfChildren = expectedNumberOfChildren; 
     this.children = new ArrayList<Node>(expectedNumberOfChildren); 
    } 
} 

지금까지 데이터 파일에서 트리를 구축, 나는 다음으로 Stack 구조를 사용합니다 : 당신은 너무 당신의 Node 어린이의 임의의 수를 처리 할 수 ​​있다는 대신 leftArrayListright를 사용할 필요가 알고리즘 (의사 코드) :

  • 빈 스택을 만듭니다.
  • "root"라는 노드 변수를 null로 초기화합니다.
  • 읽기 위해 데이터 파일을 엽니 다.
    • 다음 이름, 연도와 파일에서 아이들의 예상 수를 읽기 : 파일의 끝에 아니지만
    • .
    • 이름, 연도 및 예상되는 아동 수에서 새 노드를 만듭니다.
    • 루트 노드가 null 인 경우
      • 루트 노드를 새 노드로 설정하십시오.
      • 새 노드를 스택에 밀어 넣습니다.
    • 그렇지 않으면 :
      • 는 스택에서 마지막 노드를 (이 "부모"전화) 팝.
      • 새 노드의 부모를 스택에서 방금 튀어 나온 부모 노드로 설정하십시오.
      • 새 노드를 상위 노드의 자식 목록에 추가하십시오.
      • 부모의 자식 목록의 실제 크기가 원래 파일에서 읽은 부모의 예상 된 자식 수보다 작은 경우 부모를 다시 스택으로 밀어 넣습니다.
      • 새 노드의 예상 자식 노드 수가 0보다 큰 경우 스택에 밀어 넣습니다. 파일
  • 닫습니다.

그리고 그게 전부입니다. 루프가 끝나면 "루트"노드는 입력 파일이 올바른 형식이라고 가정하고 완전히 구성된 트리를 가리 킵니다. (스택은 더 이상 필요하지 않습니다.)