java实现二叉树的问题

来源:百度知道 编辑:UC知道 时间:2024/05/03 01:06:34
如何递归构建二叉树,可以实现把标号为1234567的点建成
1
2 3
4 5 6 7

/**
* 二叉树测试二叉树顺序存储在treeLine中,递归前序创建二叉树。另外还有能
* 够前序、中序、后序、按层遍历二叉树的方法以及一个返回遍历结果asString的
* 方法。
*/

public class BitTree {
public static Node2 root;
public static String asString;

//事先存入的数组,符号#表示二叉树结束。
public static final char[] treeLine = {'a','b','c','d','e','f','g',' ',' ','j',' ',' ','i','#'};

//用于标志二叉树节点在数组中的存储位置,以便在创建二叉树时能够找到节点对应的数据。
static int index;

//构造函数
public BitTree() {
System.out.print("测试二叉树的顺序表示为:");
System.out.println(treeLine);
this.index = 0;
root = this.setup(root);
}

//创建二叉树的递归程序
private Node2 setup(Node2 current) {
if (index >= treeLine.length) return current;
if (treeLine[index] == '#') return current;
if (treeLine[index] == ' ') return current;