该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
回复 甜味_猫 :
public class BiTree {
private BiTreeNode root;
public BiTree(String str) {
String s = str.replaceAll("#", "");
char[] chars = s.toCharArray();
root = new BiTreeNode(chars[0] + "");
root.setLchild(new BiTreeNode(chars[1] + ""));
root.setRchild(new BiTreeNode(chars[2] + ""));
root.getLchild().setLchild(new BiTreeNode(chars[3] + ""));
}
public void preRootTraverse() {
if (root != null) {
root.preRootTraverse();
} else {
System.out.println("二叉树为空");
}
}
}
class BitreeDemo{
public static void main(String[] args) {
String str = "AB##CD###";
BiTree biTree = new BiTree(str);
biTree.preRootTraverse();
}
}
class BiTreeNode{
@Override
public String toString() {
return "BiTreeNode{" +
"value='" + value + '\'' +
'}';
}
private String value;
private BiTreeNode lchild;
private BiTreeNode rchild;
//前序遍历
public void preRootTraverse(){
System.out.println(this.toString());
if(this.lchild != null) {
this.lchild.preRootTraverse();
}
if(this.rchild != null) {
this.rchild.preRootTraverse();
}
}
public BiTreeNode(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public BiTreeNode getLchild() {
return lchild;
}
public void setLchild(BiTreeNode lchild) {
this.lchild = lchild;
}
public BiTreeNode getRchild() {
return rchild;
}
public void setRchild(BiTreeNode rchild) {
this.rchild = rchild;
}
}