有序二叉树

      本文使用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();
        
    }

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值