编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。 建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
String line = scanner.next();
TreeNode2 root = build(line);
inOrder(root);
System.out.println();
}
}
private static int index = 0;
private static TreeNode2 build(String line) {
index = 0;
return creatTreePreOrder(line);
}
private static TreeNode2 creatTreePreOrder(String line) {
char cur = line.charAt(index);
if (cur == '#'){
return null;
}
TreeNode2 root = new TreeNode2(cur);
index++;
root.left = creatTreePreOrder(line);
index++;
root.right = creatTreePreOrder(line);
return root;
}
private static void inOrder(TreeNode2 root) {
}