代码
import java.util.Scanner;
class TreeNode{
int val;
TreeNode left=null;
TreeNode right=null;
public TreeNode(int val) {
this.val=val;
}
}
public class CreateBinaryTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
TreeNode root1=creatTree(in);
display(root1);
System.out.println();
}
private static void display(TreeNode root) {
// TODO Auto-generated method stub
if (root!=null) {
System.out.print(root.val+" ");
display( root.left);
display(root.right);
}
}
private static TreeNode creatTree(Scanner in) {
// TODO Auto-generated method stub
TreeNode newNode;
int val=in.nextInt();
if (val==-1) { //设置 -1 为结束数字
val=in.nextInt();
}
if (val!=0) { // 0 代表空节点
newNode=new TreeNode(val);
}else {
newNode=null;
return null;
}
newNode.left=creatTree(in);
newNode.right=creatTree(in);
return newNode;
}
}
测试结果: