class Student
{
String name;
int roll;
int age;
public Student(String n,int r,int a) {
name=n;
roll=r;
age=a;
}
public String retname() {
return name;
}
public int retroll() {
return roll;
}
public int retage() {
return age;
}
public void displaystudent() {
System.out.print("Name : "+name+" Roll : "+roll+" Age : "+age+"\n");
}
}
class Node
{
Student s;
Node lchild;
Node rchild;
public Node(String n,int r ,int a) {
s=new Student(n,r,a);
}
public void displayNode() {
s.displaystudent();
}
}
class Tree
{
public Node root;
public void insert(String n,int r,int a) {
Node newNode=new Node(n,r,a);
if(root==null)
root=newNode;
else {
Node current=root;
Node parent;
while(true) {
parent=current;
if(n.compareTo(current.s.retname())<0) {
current=current.lchild;
if(current==null)
parent.lchild=newNode;
return;
} else {
current=current.rchild;
if(current==null)
parent.rchild=newNode;
return;
}
}
}
}
public void order() {
inorder(root);
preorder(root);
postorder(root);
}
public void inorder(Node localroot) {
if(localroot!=null) {
inorder(localroot.lchild);
localroot.displayNode();
inorder(localroot.rchild);
}
}
public void preorder(Node localroot) {
if(localroot!=null) {
preorder(localroot.lchild);
preorder(localroot.rchild);
localroot.displayNode();
}
}
public void postorder(Node localroot) {
if(localroot!=null) {
localroot.displayNode();
postorder(localroot.lchild);
postorder(localroot.rchild);
}
}
}
class e
{
public static void main(String [] args) { //throws IOException
Tree t=new Tree();
t.insert("E",1,23);
t.insert("D",2,2);
t.insert("C",3,4);
t.insert("B",4,89);
t.insert("A",5,45);
t.order();
}
}
上面的代碼沒有顯示它應該的所有輸出。另外,爲什麼前序和中序給出了相同的結果? 另外,如何在不從根開始的子樹中進行遍歷? 有什麼辦法可以避免遞歸嗎?二分查找樹
這是當前不正確的輸出。它應該打印我插入的所有元素,也以特定順序打印。
Name : D Roll : 2 Age : 2
Name : E Roll : 1 Age : 23
Name : D Roll : 2 Age : 2
Name : E Roll : 1 Age : 23
Name : E Roll : 1 Age : 23
Name : D Roll : 2 Age : 2
你得到了什麼輸出,你期望它能告訴你什麼? – 2015-03-18 21:27:21
@BradySheehan'姓名:D卷:2年齡:2 姓名:E卷:1年齡:23 姓名:D卷:2年齡:2 姓名:E卷:1年齡:23 姓名:E卷:1年齡:23 名稱:D卷:2年齡:2'這是當前的輸出。它應該打印我插入的所有元素,並按特定順序打印。 – user4275686 2015-03-18 21:35:12