-3
我正在創建一個樹形結構,但問題是在輸入顯示時它不顯示任何東西。也許是因爲根目前仍然是空的,我不明白爲什麼。如何在Java中創建樹結構?
public class Tree extends LLQueue {
int data12;
tree left;
tree right;
@Override
public int getdata(){
return data12;
}
@Override
public void setdata(int data){
this.data12 =data;
}
public tree getleft(){
return left;
}
public void setleft(tree left){
this.left=left;
}
public tree getright(){
return right;
}
public void setright(tree right){
this.right =right;
}
public static void main(String args[]) throws IOException, EmptyQueueException{
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter option ");
int n =Integer.parseInt(br.readLine());
tree root =null;
do{
System.out.println("\nQueue Operations");
System.out.println("1. insert");
System.out.println("2. display");
int choice = Integer.parseInt(br.readLine());
switch(choice){
case 1:
System.out.println("insert here");
int input =Integer.parseInt(br.readLine());
insertintree(root,input);
break;
case 2:
System.out.println("result is");
preorder(root);
}
}while(n!=0);
}
private static void insertintree(tree root, int input) throws EmptyQueueException {
LLQueue Q =new LLQueue();
tree temp = null;
int temp1;
tree newnode =new tree();
newnode.setdata(input);
newnode.setleft(null);
newnode.setright(null);
if(newnode ==null){
System.out.println("memory error");
return;
}
if(root ==null){
root =newnode;
return;
}
Q.enQueue(root.getdata());
while(!Q.isEmpty()){
temp1=Q.deQueue();
temp.setdata(temp1);
if(temp.getleft()!=null){
tree temp2 =temp.getleft();
Q.enQueue(temp2.getdata());
}
else
{
temp.setleft(newnode);
Q.deQueue();
return;
}
if(temp.getright()!=null){
tree temp2 =temp.getright();
Q.enQueue(temp2.getdata());
}
else
{
temp.setright(newnode);
Q.deQueue();
return;
}
}
Q.deQueue();
}
private static void preorder(tree root) {
if(root!=null){
System.out.println(root.getdata());
preorder(root.getleft());
preorder(root.getright());
}
}
}
爲了更好地幫助越早,張貼[MCVE ](http://stackoverflow.com/help/mcve)。 – 2014-09-22 17:46:25
'root'保持爲空,因爲您永遠不會爲其指定值。 – azurefrog 2014-09-22 17:47:49
看看[is-java-pass-by-reference-or-pass-by-value](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass以獲取更多信息。 – azurefrog 2014-09-22 17:54:56