容易理解的递归创建方式


import java.util.Scanner;

class TreeNode1{
    public char val;
    public TreeNode1 left;
    public TreeNode1 right;

    public TreeNode1(char val) {
        this.val = val;
    }
}



public class Main {
    public static int i = 0;
    public static TreeNode1 createTree(String str){
        TreeNode1 root = null;
        
        if (str.charAt(i) != '#') {
            root = new TreeNode1(str.charAt(i));
            i++;
            root.left = createTree(str);
            root.right = createTree(str);
        } else {
            i++;
        }
        return root;
    }

    public static void inOrderTraversal(TreeNode1 root){
        if (root == null) {
            return;
        }
        inOrderTraversal(root.left);
        System.out.print(root.val+" ");
        inOrderTraversal(root.right);
    }


    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while (scan.hasNextLine()) {
            String str = scan.nextLine();
            TreeNode1 root = createTree(str);
            inOrderTraversal(root);
        }

    }
}