java一個簡單的二叉樹
package it.cast;
import java.util.List;
public class BTree {
private BTree leftChild;
private BTree rightChild;
private BTree root;
private Object data;
public BTree(BTree leftChild, BTree rightChild, Object data) {
this.leftChild = leftChild;
this.rightChild = rightChild;
this.data = data;
}
// 建立構造方法,用於接收BTree中的資料
public BTree(Object data) {
this(null, null, data);
}
public BTree() {
}
// 建立樹
public void CreateBtree(Object[] obj) {
BTree[] b = new BTree[obj.length];
for (int i = 0; i < obj.length; i++) {
BTree ss = new BTree(obj[i]);// 將資料封裝成樹節點
b[i] = ss;// 傳入陣列中
}
root = b[0];// 將第一個數放入根節點中
// 按左右的循序放入節點
for (int i = 0; i < b.length / 2; i++) {
// 奇數位的資料放入左節點中
b[i].leftChild = b[2 * i + 1];
if (2 * i + 2 < b.length) {// 判斷偶數位是否溢位
b[i].rightChild = b[2 * i + 2];
}
}
}
//先序遍歷
public void preorder(BTree b) {
if (b != null) {
visit(b.getData());
preorder(b.leftChild);
preorder(b.rightChild);
}
}
//中序遍歷
public void middens(BTree b) {
if(b!=null) {
middens(b.leftChild);
visit(b.getData());
middens(b.rightChild);
}
}
//後序遍歷
public void After(BTree b) {
if(b!=null) {
After(b.leftChild);
After(b.rightChild);
visit(b.getData());
}
}
private void visit(Object data2) {
System.out.print(data2 + " ");
}
private Object getData() {
return data;
}
private BTree getRoot() {
return root;
}
public static void main(String[] args) {
BTree b = new BTree();
Object[] obj = { 0, 1, 2, 3, 4, 5, 6, 7 };
b.CreateBtree(obj);
b.preorder(b.getRoot());
System.out.println();
b.middens(b.getRoot());
System.out.println();
b.After(b.getRoot());
}
}