请大家帮忙~
要求层次遍历二叉树,但是遍历到E时,出现错误Exception in thread "main" java.lang.NullPointerException,遍历不到F~我的代码是这样的:
//二叉树节点类
class BTNode {
public char data;
public BTNode left,right;
public BTNode(char data) {
this.data = data;
} public char getData() {
return data;
} public void setData(char data) {
this.data = data;
} public BTNode getLeft() {
return left;
} public void setLeft (BTNode left) {
this.left = left;
} public BTNode getRight() {
return right;
} public void setRight (BTNode right) {
this.right = right;
}
}class BT {
public BTNode root;
public void BinTree (BTNode root) {
this.root = root;
} public BTNode getRoot() {
return root;
}
//先序建立二叉树
BTNode a,b,c,d,e,f;
public BTNode init() {
a = new BTNode('A');
b = new BTNode('B');
d = new BTNode('D');
e = new BTNode('E');
c = new BTNode('C');
f = new BTNode('F');
a.setLeft(b);
a.setRight(c);
b.setLeft(d);
b.setRight(e);
c.setRight(f);
return a; //树根
} //访问节点
public void visit(BTNode p) {
System.out.print(p.getData()+"->");
}
public void order(BTNode p) {
if (p !=null) {
if (p.getLeft() !=null) {
visit(p.getLeft());
}
if (p.getRight() !=null) {
visit(p.getRight());
}
}
order(p.getLeft());
order(p.getRight());
}
}public class BinTree {
public static void main(String args[]) {
BT tree = new BT();
tree.BinTree(tree.init());
System.out.print("层序遍历:");
tree.visit(tree.getRoot());
tree.order(tree.getRoot());
}
}
要求层次遍历二叉树,但是遍历到E时,出现错误Exception in thread "main" java.lang.NullPointerException,遍历不到F~我的代码是这样的:
//二叉树节点类
class BTNode {
public char data;
public BTNode left,right;
public BTNode(char data) {
this.data = data;
} public char getData() {
return data;
} public void setData(char data) {
this.data = data;
} public BTNode getLeft() {
return left;
} public void setLeft (BTNode left) {
this.left = left;
} public BTNode getRight() {
return right;
} public void setRight (BTNode right) {
this.right = right;
}
}class BT {
public BTNode root;
public void BinTree (BTNode root) {
this.root = root;
} public BTNode getRoot() {
return root;
}
//先序建立二叉树
BTNode a,b,c,d,e,f;
public BTNode init() {
a = new BTNode('A');
b = new BTNode('B');
d = new BTNode('D');
e = new BTNode('E');
c = new BTNode('C');
f = new BTNode('F');
a.setLeft(b);
a.setRight(c);
b.setLeft(d);
b.setRight(e);
c.setRight(f);
return a; //树根
} //访问节点
public void visit(BTNode p) {
System.out.print(p.getData()+"->");
}
public void order(BTNode p) {
if (p !=null) {
if (p.getLeft() !=null) {
visit(p.getLeft());
}
if (p.getRight() !=null) {
visit(p.getRight());
}
}
order(p.getLeft());
order(p.getRight());
}
}public class BinTree {
public static void main(String args[]) {
BT tree = new BT();
tree.BinTree(tree.init());
System.out.print("层序遍历:");
tree.visit(tree.getRoot());
tree.order(tree.getRoot());
}
}
public void order(BTNode p)
{
if (p !=null)
{ if (p.getLeft() !=null)
{
visit(p.getLeft());
}
if (p.getRight() !=null)
{
visit(p.getRight());
}
order(p.getLeft());//这两句放里面来
order(p.getLeft());
}
}