2017-04-04 3 views
0

BST 데이터 구조를 사용하여 문자열 이름과 Int 가중 값을 모두 가진 15 개의 노드를 정렬하는 데이터 구조 클래스의 숙제를 작업 중입니다. 클래스에 사용할 핵심 값은 문자열 이름입니다. 여기 내 코드는 지금까지 모습입니다 : 그러나내 모든 BST 트래버스가 순서대로 값을 반환하는 이유는 무엇입니까?

import java.util.Scanner; 
/** 
* 
* @author daniel 
*/ 
public class Assignment3 { 
public static void main(String args[]){ 
    Scanner keyboard = new Scanner(System.in); 
    Tree BST = new Tree(); 
    //Add 15 names and weights to Tree 
    for(int i = 0; i < 15; i++){ 
     Node newNode = new Node(keyboard.next(), keyboard.nextInt()); 
     BST.insert(newNode.name); 
    } 

    System.out.print("Post: \n"); 
    BST.postorder(); 
    System.out.print("\nPre: \n"); 
    BST.preorder(); 
    System.out.print("\nIn: \n"); 
    BST.inorder(); 
} 
} 

class Node{ 
Node left, right; 
int weight; 
String name; 
//Constructors 
public Node(String n){ 
    left = null; 
    right = null; 
    name = n; 
} 

public Node(String n, int w){ 
    left = null; 
    right = null; 
    name = n; 
    weight = w; 
} 
} 

class Tree{ 
private Node root; 

public Tree(){ 
    root = null; 
} 
//Insertion Method 
public void insert(String name){ 
    root = insert(root, name); 
} 
//Insert Recursively 
private Node insert(Node node, String name){ 
    if(node == null){ 
     node = new Node(name); 
    }else{ 
     int compare = name.compareToIgnoreCase(node.name);   
     if(compare < 0){node.left = insert(node.left, name);} 
     else{node.right = insert(node.right, name);} 
    } 
    return node; 
} 
//Inorder Traversal 
public void inorder(){inorder(root);} 
public void inorder(Node current){ 
    if(current != null){ 
     inorder(current.left); 
     System.out.print(current.name + " "); 
     inorder(current.right); 
    } 
} 
//Postorder Traversal 
public void postorder(){inorder(root);} 
public void postorder(Node current){ 
    if(current != null){ 
     postorder(current.left); 
     postorder(current.right); 
     System.out.print(current.name + " "); 

    } 
} 
//Preorder Traversal 
public void preorder(){inorder(root);} 
public void preorder(Node current){ 
    if(current != null){ 
     System.out.print(current.name + " "); 
     preorder(current.left); 
     preorder(current.right); 
    } 
} 
} 

, 내 코드를 실행하면, 모든 순회은 알파벳 순서대로 값을 반환합니다. n은 1 B 2 C 3 전 4 5 R 6 B 7 Q 8 P 9 H 10 Y 11t 12 Z 13w 14 X 15

출력 : 글 : abbchinpqrtwxyz 여기

내 입력 된

사전 : 에서

abbchinpqrtwxyz : 이 내가 데이터에 넣어 방법에 관계없이입니다

abbchinpqrtwxyz. 다른 데이터를 입력하기 위해 여러 번 시도했지만 잘못된 점을 알지 못합니다. 내 삽입 방법과 관련이 있다고 생각하지만 여기서 어디로 가야할지 모르겠습니다. 당신의 도움을 주셔서 감사합니다.

답변

3
public void postorder(){inorder(root);} // why is this inorder(root), it should be postorder(root), change it same with preorder. 
public void postorder(Node current){ 
if(current != null){ 
    postorder(current.left); 
    postorder(current.right); 
    System.out.print(current.name + " "); 

    } 
} 
+0

예수 그리스도. 감사. – Daniel

+1

아, 복사 '붙여 넣기의 위험성. –