给定一个二叉树,找出其最大的深度,Java递归实现

本文介绍了一种通过递归方式计算二叉树高度的方法。详细解释了如何对比左右子树高度,选取较大值并加一的过程,最终得到整棵树的高度。
/**
 * 返回二叉树的深度,二叉树的高度
 */
public class MaxDeepOfBinaryTree {


    /**
     * 使用递归获取二叉树的高度
     * @param root 二叉树
     * @return 二叉树的高度
     */
    public static int getHeight(BinaryTree root){
        //如果节点为空则返回0
        if(root == null){
            return 0;
        //否则比较左子树和右子树的高度,返回更大的值
        }else {
            int leftTreeHeight = getHeight(root.left);
            int rightTreeHeight = getHeight(root.right);
            //可以使用三目表达式,也可调用静态函数
//            int x = leftTreeHeight > rightTreeHeight?leftTreeHeight:rightTreeHeight;
            return Math.max(leftTreeHeight, rightTreeHeight) + 1;
        }

    }


    public static void main(String[] args){
        BinaryTree head  = new BinaryTree(1);
        BinaryTree left  = new BinaryTree(2);
        BinaryTree right  = new BinaryTree(3);
        BinaryTree left01  = new BinaryTree(4);
        BinaryTree right01  = new BinaryTree(5);
        head.left = left;
        head.right = right;
        left.left = left01;
        left.right = right01;

        System.out.println(getHeight(head));
        System.out.println("-----------");
        //返回3
    }
}


//二叉树的类
class BinaryTree{
    int value;
    BinaryTree left;
    BinaryTree right;

    public BinaryTree(int value){
        this.value = value;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值