createBiTree()没有改变 tn 的内容,为什么。请指教import java.io.*;
import java.util.*; class TreeNode{//节点类
private String data;
public TreeNode lchild,rchild;
public TreeNode(String d){// 节点构造函数
System.out.println("node created");
this.data = d;
this.lchild = null;
this.rchild = null;
}
public TreeNode(){// 节点构造函数
System.out.println("node created");
this.data = "abc";
this.lchild = null;
this.rchild = null;
}
public void visitNode(){//输出节点
System.out.println(data);
}
}
public class BiTree{
public BiTree(){//主类构造函数
TreeNode tn = new TreeNode();//建立新树根为空
try{//建立二叉树
createBiTree(tn);
}catch(IOException e){
e.printStackTrace();
}
tn.visitNode();
outputTree(tn);//按层输出二叉树
}
String instr;
String over = new String(" ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public void createBiTree(TreeNode tn)throws IOException{//从键盘输入字符串,按先序次序输入并创建二叉树
TreeNode t = tn;
System.out.println("input node");
try{//从键盘输入节点数据
instr = br.readLine();
}catch(IOException e){
e.printStackTrace();
}
if(instr.equals(over)){//如果为空则表示没有节点
tn = null;
}
else{//否则建立节点,并为该节点的左孩及右孩子建立节点如此循环
t = new TreeNode(instr);
createBiTree(t.lchild);
createBiTree(t.rchild);
}
}
public void outputTree(TreeNode tn){//二叉树按层输出,传入参数树根
LinkedList ll = new LinkedList();//建立一个队列
ll.addLast(tn);//根入队列尾
while(!(ll.isEmpty())){//如果栈里有元素,取第一个队列第一个元素并输出
TreeNode tn1 = (TreeNode)ll.getFirst();
tn1.visitNode();//产生了空指针异常,为什么
ll.removeFirst();//移出第一个元素
if(!(tn1.lchild==null)){//如果有左孩子,将其加入队列尾
ll.addLast(tn1.lchild);
}
if(!(tn1.rchild==null)){
ll.addLast(tn1.rchild);
}
}
}
public static void main(String args[]){//程序入口
BiTree bt =new BiTree();
}
}

解决方案 »

  1.   

    从键盘输入节点数据的顺序是a回车b回车c回车空格回车空格回车d回车e回车空格回车g回车空格回车
    空格回车f回车空格回车空格回车,就是abc__de_g__f___,"_"代表空格就是空数据
      

  2.   

    在我这里没有发生任何的异常,全部输入与输出如下:
    -----------------------
    node creat
    input node
    a
    node creat
    input node
    b
    node creat
    input node
    c
    node creat
    input nodeinput nodeinput node
    d
    node creat
    input node
    e
    node creat
    input nodeinput node
    g
    node creat
    input nodeinput nodeinput node
    f
    node creat
    input nodeinput nodeinput nodeabc
    abc--------------------------------
      

  3.   

    else{//否则建立节点,并为该节点的左孩及右孩子建立节点如此循环
    t = new TreeNode(instr);
    createBiTree(t.lchild);
    createBiTree(t.rchild);
    }如果输入非空字符,你的createBiTree无法结束,所以根本没有运行outputTree
    即使输入空字符,你也没有将输入存入列表