2017-04-04 43 views
0

我正在爲我的數據結構類使用BST數據結構來排序15個節點的家庭作業分配,這15個節點同時具有字符串名稱和Int重量值。我應該用於該類的關鍵值是字符串名稱。這裏是我的代碼看起來像至今:爲什麼我所有的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 I 4 5,R 6 b 7分配Q 8第9頁H 10ÿ11噸12瓦特13 Z 14×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

啊,複製粘貼的危險。 –