二叉树的遍历,得不到想要的结果
第一个类
public class BiTreeNode {
public Object data;
public BiTreeNode lChild,rChild;
public BiTreeNode() {
this(null);
}
public BiTreeNode(Object data) {
this(data,null,null);
}
public BiTreeNode(Object data,BiTreeNode lChild,BiTreeNode rChild) {
this.data=data;
this.lChild=lChild;
this.rChild=lChild;
}
}
第二个类
public class BiTree {
public BiTreeNode root;
public BiTree() {
this.root =null;
}
public BiTree(BiTreeNode root) {
this.root =root;
}
public void preRootTraverse(BiTreeNode t) {
if (t!=null) {
System.out.println(t.data);
preRootTraverse(t.lChild);
preRootTraverse(t.rChild);
}
}
public void inRootTraverse(BiTreeNode t) {
if (t!=null) {
inRootTraverse(t.lChild);
System.out.println(t.data);
inRootTraverse(t.rChild);
}
}
public void postRootTraverse(BiTreeNode t) {
if (t!=null) {
postRootTraverse(t.lChild);
postRootTraverse(t.rChild);
System.out.println(t.data);
}
}
}
第三个测试类
public class Text {
public BiTree creatBiTree() {
BiTreeNode e=new BiTreeNode('E');
BiTreeNode c=new BiTreeNode('C');
BiTreeNode d=new BiTreeNode('D');
BiTreeNode b=new BiTreeNode('B',d,e);
BiTreeNode a=new BiTreeNode('A',b,c);
return new BiTree(a);
}
public static void main(String[] args) {
Text text=new Text();
BiTree biTree=text.creatBiTree();
BiTreeNode root=biTree.root;
System.out.print("递归先根遍历");
biTree.preRootTraverse(root);
System.out.println();
System.out.print("递归中根遍历");
biTree.inRootTraverse(root);
System.out.println();
System.out.print("递归后根遍历");
biTree.postRootTraverse(root);
System.out.println();
}
}
你第一个类的第三个构造函数错了,this.rChild=lChild;--》你可能打快了
解决:this.rChild=rChild;
public void preRootTraverse(BiTreeNode t) {
System.out.println(t.data);
if (t.lChild!=null) {
preRootTraverse(t.lChild);
}
if (t.rChild!=null) {
preRootTraverse(t.rChild);
}
}
其他2个类似修改