import java.util.*;
class TreeNode {
public char val;
public TreeNode left;
public TreeNode right;
public TreeNode(char val) {
this.val = val;
}
}
public class Main {
//由于下面递归的时候i不能每次从0开始 所以把i写在外面
public static int i = 0;
public static TreeNode creteTree(String str) {
TreeNode root = null;
//如果charAt(i) == '#' 说明根的左子树或者右子树为空了 就直接返回root了
if(str.charAt(i) != '#') {
root = new TreeNode(str.charAt(i));
i++;
root.left = creteTree(str);
root.right = creteTree(str);
} else {
i++;
}
return root;
}
public static void inorder(TreeNode root) {
if(root == null) return;
inorder(root.left);
System.out.print(root.val+" ");
inorder(root.right);
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
//创建一棵树
TreeNode root = creteTree(str);
//中序遍历这棵树
inorder(root);
}
}
二叉树遍历
最新推荐文章于 2025-07-01 14:00:00 发布