本文使用java写的有序二叉树,所谓有序二叉树,就是左子树上的数值小于树根上的值,树根的值小于右子树的值,创建过程很简单,只需要加上一个判断就可以,至于遍历,前序,中序,后序遍历需要使用栈来完成,于是使用递归的方法,层序遍历则需要使用队列,就是先将树根加到队列,然后每次取出队首元素,输出值,并将左右子树加入队列,循环至队列为空为止。下面是主要代码:
import java.util.LinkedList;
import java.util.Queue;
class BiTree {
private int n; //数据域
private BiTree l; //左子树
private BiTree r; //右子树
public BiTree(int n) {
this.n = n;
}
//添加子树
public void add(BiTree x) {
//如果添加的树的值小于树根的值,加到左子树
if (x.n < n) {
//若左子树为空,则加上
if (l == null) {
l = x;
}
//左子树不空,则将左子树作为树根,继续添加
else {
l.add(x);
}
}
else {
if (r == null) {
r = x;
} else {
r.add(x);
}
}
}
//中序遍历
public void midTravel() {
if (l != null) {
l.midTravel();
}
System.out.print(n + " ");
if (r != null) {
r.midTravel();
}
}
//层序遍历
public void levTravel() {
Queue<BiTree> que = new LinkedList<BiTree>();
BiTree root = this;
que.add(root);
while(!que.isEmpty()) {
root = que.remove();
System.out.print(root.n + " ");
if(root.l != null) {
que.add(root.l);
}
if(root.r != null) {
que.add(root.r);
}
}
}
//计算树高
public int getHeight() {
int hl, hr;
if (l == null)
hl = 0;
else
hl = l.getHeight();
if (r == null)
hr = 0;
else
hr = r.getHeight();
return Math.max(hl, hr) + 1;
}
}
public class BiTreeTest {
public static void main(String[] args) {
BiTree bt = new BiTree(1);
bt.add(new BiTree(3));
bt.add(new BiTree(5));
bt.add(new BiTree(7));
bt.add(new BiTree(9));
bt.levTravel();
System.out.println();
}
}