一、定义二叉树节点类

 package tree;

 public class Node<E> {
public E data;
public Node<E> lnode;
public Node<E> rnode; public Node(){}
public Node(E data) {
this.data = data;
}
}

  通过泛型(generics)定义了一个公有的节点类,包含一个数据域 data,以及两个引用域 lnode 和 rnode。构造函数提供有参和无参默认两种。当然,因为二叉树节点这个类的适用范围是在关于二叉树的操作中,所以更加完美的做法是将其作为私有内部类定义。

二、定义二叉树主类

 public class BiTree <E> {

     /** root node of the binary tree    */
private Node<E> root;
/** the gross of total leaves */
private int leaveGross;
private int depth;
private String name; public BiTree(String name) {
this.name = name;
root = new Node<>();
} public Node<E> getRoot() { return root; } public int getLeaveGross() { return leaveGross; } public String getName() { return name; } public int getDepth() { return depth(root); } public int depth(Node<E> root){
if(root != null) {
return Math.max(depth(root.lnode), depth(root.rnode)) + 1;
} else
return 0;
}
}

  这里最主要的是根节点信息 root, 它是二叉树的构建、遍历、求深度、求叶子总数的根本。其他属性,可以有选择的定义。这里我递归写了一个求二叉树深度的方法。

三、构造二叉树

  在主类<code>BiTree</code>中定义建立二叉树的方法 -- generate()。

     /**
* Construct a Binary Tree with a given sequence of data as form of array.
* The <code>data</code> should be given as a complete binary tree.
* @param data
* @author SheepCore@MarshallLee
*/
public void generate(E[] data){
if(data.length == 0)
return;
int numData = data.length;
Node<E>[] nodes = new Node[numData]; for (int i = 0; i < numData; i++) {
nodes[i] = new Node(data[i]);
} for (int i = 0; i < numData / 2; i++) {
nodes[i].lnode = nodes[2 * i + 1];
nodes[i].rnode = nodes[2 * i + 2] ;
}
this.root = nodes[0];
depth = getDepth();
leaveGross = numData;
}
05-28 01:41