2017-04-04 46 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

啊,复制粘贴的危险。 –