JAVA数据结构--根据树高生成完全二叉树(java实现)

本文介绍了一个二叉树类的实现,包括根据指定高度初始化二叉树的方法及统计树中节点总数的递归算法。通过实例演示了如何创建特定高度的二叉树并计算其节点数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class BTree {
    private int node;
    private BTree LChild ;
    private BTree RChild ;

    private BTree(int node){
        this.node = node;
        LChild = null;
        RChild = null;
    }
    public BTree getL(){
        return LChild;
    }
    public BTree getR(){
        return RChild;
    }
    public void setL(BTree L){
        this.LChild = L;
    }
    public void setR(BTree R){
        this.RChild = R;
    }
    public int getNode(){
        return node;
    }
    /**
     * 根据树高建树
     * @param num
     * @return
     */
    public static BTree InitBTree(int num){

        if(num == 0){
            return null;
        }
        BTree root = new BTree(num);
        root.setL(InitBTree(num-1));
        root.setR(InitBTree(num-1));
        return root;
    }
    /**
     * 统计节点个数
     * @param node
     * @return
     */
    public static int getNodeNum(BTree node){
        if(node.getL()==null && node.getR()==null)
            return 1;
        return getNodeNum(node.getL()) + getNodeNum(node.getR()) + 1;
    }
    public static void main(String[] args){
        BTree root2 = InitBTree(3);
        System.out.println(getNodeNum(root2));

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值