最近在刷剑指offer,里面提到二叉树,一直以来用java的多,所以编写了一个java二叉树结构和工具类。工具类包括创建,遍历等方法。定期更新。
关于输入,假如我的二叉树结构为,则输入的数据为1 2 0 0 3 0 0 。如果为,则输入数据为 1 2 3 0 0 0 4 0 5 0 0
,其中空格应该为换行。采取的是先序输入。如果要改为中序,则可以用栈。以下是代码。
class TreeNode {
public int val ;
public TreeNode left ;
public TreeNode right ;
public TreeNode(int val){
this.val = val;
}
}
public class TreeBinaryFunction {
public static TreeNode CreateTreeBinary(TreeNode treeNode){
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
if(num == 0){
return null;
}
else{
treeNode.val = num;
treeNode.left = CreateTreeBinary(new TreeNode(0));
treeNode.right = CreateTreeBinary(new TreeNode(0));
return treeNode;
}
}
public static void PrintTreeBinary(TreeNode treeNode){
if(treeNode!=null){
System.err.println(treeNode.val);
PrintTreeBinary(treeNode.left);
PrintTreeBinary(treeNode.right);
}
}
}