二叉树遍历算法的应用(java版)

1.统计二叉树中节点的个数
思路:统计二叉树节点个数,无次序的要求,按照一种次序遍历,遇到节点count++即可。
代码:

/*
     * 先根序统计节点的个数
     */
    private int count = 0;
    public void calculateNodeCount(Btree<T> root){
        if (root != null) {
            count++;
            calculateNodeCount(root.left);
            calculateNodeCount(root.right);
        }
    }

    public int  getNodeCount(Btree<T> root){
        calculateNodeCount(root);

        return count;
    }

2.输出二叉树的叶子节点
思路:三种遍历方式输出的二叉树叶子节点的次序是一样的,因此可以选择任意一种,但是输出叶子节点,则遍历过程中,每个节点均测试是否满足叶子节点的条件。

/*
     * 采用中根序法遍历
     */
    public void printLeaves(Btree<T> root){
        if (root != null) {
            printLeaves(root.left);
            if (root.left == null && root.right == null) {
                visitDate(root);
            }
            printLeaves(root.right);
        }
    }

3.统计叶子节点的数目
方法1:使用全局变量,参看上述例子,将visitDate(…)变成count++,统计即可。
方法2:通过函数返回值的方法。采用递归的思想,如果是空树,则返回0;如果是叶子,则返回1;否则,返回左右字数的节点之和。必须在左右字数的叶子节点求出来之后,才能求出叶子节点,因此采用后序遍历。

public int getLeavesCount(Btree<T> root){
        int nr = 0;
        int nl = 0;

        if (root == null) {
            return 0;
        }

        if (root.left == null && root.right == null) {
            return 1;
        }

        nl = getLeavesCount(root.left);
        nr = getLeavesCount(root.left);

        return nl + nr;
    }

4.求二叉树的高度
方法一:使用全局变量的方法。二叉树的根节点为第一层的节点,第h层节点的孩子在h+1层,故增设层次参数h,通过递归调用参数的变化,获得二叉树中每个节点的层次,用全局变量记录二叉树中节点层次的最大值,就是二叉树的高度。

/*
     * 得到树的高度
     */
    private int depth = 0;
    public void getTreeDepth(Btree<T> root, int h){
        //h为root节点所在的层次。首次调用时,初始值为1
        //depth是记录当前求得的最大层次的全局变量,调用前的初始值为0
        if (root != null) {
            if (h > depth) {
                depth = h;
            }
            getTreeDepth(root.left , h+1);
            getTreeDepth(root.right, h+1);
        }
    }

方法二:通过函数的返回值方法,采用递归的思想,如果是空树,则树的高度为0;否则树的高度为左子树和右子树的最大值加1.此方法中必须在左右字数的高度计算出来后,才可求出树的高度,因此用后序遍历。

public int treeDepth(Btree<T> root){
        int hl = 0;
        int hr = 0;
        int h = 0;

        if (root == null) {
            return 0;
        }else{
            hl = treeDepth(root.left);
            hr = treeDepth(root.right);

            h = Math.max(hl, hr) + 1;

            return h;
        }
    }

5.求节点的双亲
思路:在遍历过程中,若当前节点非空且当前节点的左孩子或右孩子就是特定的节点,则已找到双亲,否则在左子树中找到,找到,则返回双亲的指针,未找到,则在右子树中找。

public Btree<T> getParent(Btree<T> root,Btree<T> current){
        Btree<T> p = null;
        if (root == null) {
            return null;
        }

        if (root.right == current || root.left == current) {
            return root;
        }

        p = getParent(root.left,current);
        if (p != null) {
            return p;
        }else{
            return getParent(root.right,current);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值