题目要求:
思路:创建一个树,通过Scanner获取字符串,使用Index来记录字符串的下标,每次++,如果为#则不放入树中,递归实现前序遍历,然后递归实现中序遍历即可
import java.util.*;
public class Main {
public static class TreeNode {
public char val;
public TreeNode left;
public TreeNode right;
public TreeNode(char val){
this.val = val;
}
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine()){
String s = scan.nextLine();//接收scan获取的字符
TreeNode root = create(s);
InOrder(root);
}
}
public static void InOrder(TreeNode root){
if(root == null){
return;
}
InOrder(root.left);
System.out.print(root.val+" ");
InOrder(root.right);
}
static int Index = 0;
public static TreeNode create(String s){
TreeNode root = null;
if(s.charAt(Index) != '#'){
root = new TreeNode(s.charAt(Index));
Index++;//每次++获取到下一个字符
root.left = create(s);
root.right = create(s);
}else{
Index++;
}
return root;
}
}