以字符串的形式定义一棵二叉树的先序序列,若字符是‘#’, 表示该二叉树是空树,否则该字符是相应结点的数据元素。读入相应先序序列,建立二叉链式存储结构的二叉树,然后中序遍历该二叉树并输出结点数据。
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str;
str = in.next();
BinaryTree test = new BinaryTree(str);
test.toString(test);
}
}
class BinaryTree {
char data;
BinaryTree lchild, rchild;
BinaryTree fa;
int endSign = 0;
BinaryTree() {
this.lchild = null;
this.rchild = null;
this.fa = null;
}
BinaryTree(String str) {
endSign = 0;
BinaryTree root = new BinaryTree();
root = this;
BinaryTree fatemp = new BinaryTree();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) != '#') {
root.data = str.charAt(i);
if (root.lchild == null) {
root.lchild = new BinaryTree();
fatemp = root;
root = root.lchild;
root.fa = fatemp;
} else if (root.rchild == null) {
root.rchild = new BinaryTree();
fatemp = root;
root = root.rchild;
root.fa = fatemp;
}
} else {
root.data = '#';
if(i <str.length()-1) {
root = root.fa;
root = Find(root);
}
}
}
}
// void addLc(char data) {
// this.lchild = new BinaryTree();
// this.lchild.data = data;
// }
// void addRc(char data) {
// this.rchild = new BinaryTree();
// this.rchild.data = data;
// }
BinaryTree Find(BinaryTree child) {
BinaryTree fatep = new BinaryTree();
if (child.rchild == null) {
child.rchild = new BinaryTree();
fatep = child;
child = child.rchild;
child.fa = fatep;
return child;
}else
return Find(child.fa);
}
public void toString(BinaryTree root) {
if(root.data != '#') {
toString(root.lchild);
System.out.print(root.data);
toString(root.rchild);
}
}
}