求二叉树的深度

一,Leetcode104 求二叉树的最大深度

在这里插入图片描述

//递归
public int maxDepth(TreeNode root) {
        return getDepth(root);
    }
	
	//左右子树的高度因为递归都是从下向上计算
    public int getDepth(TreeNode root){
    //终止条件就是出现空节点,高度也就是0
        if(root==null) return 0;
        int leftDepth=getDepth(root.left);
        int rightDepth=getDepth(root.right);
        return (leftDepth>rightDepth?leftDepth:rightDepth)+1;
    }
//层序遍历加个计数器即可,最大深度即为二叉树的层数
public int maxDepth(TreeNode root) {
        if(root==null) return 0;
        Queue<TreeNode> queue=new LinkedList<>();
        int depth=0;
        queue.offer(root);
        while(!queue.isEmpty()){
            int size=queue.size();
            depth++;            
            for(int i=0;i<size;i++){
                TreeNode node=queue.poll();
                if(node.left!=null) queue.offer(node.left);
                if(node.right!=null) queue.offer(node.right);
            }
        }
        return depth;
    }

类似题目:Leetcode559,N叉树的最大深度

二,111,二叉树的最小深度
在这里插入图片描述

//递归实现,相比较求最大深度,最重要的点在于:当左子树为空的时候,最小深度其实为右子树的深度而并非1.需要添加条件来避免这种错误。
public int minDepth(TreeNode root) {
        return getMinDepth(root);
    }

    public int getMinDepth(TreeNode root){
        if(root==null) return 0;
        int leftDepth=getMinDepth(root.left);
        int rightDepth=getMinDepth(root.right);
        //以下的if语句是避免误区的关键条件
        if(leftDepth==0){
            return rightDepth+1;
        }
        if(rightDepth==0){
            return leftDepth+1;
        }
        return (leftDepth>rightDepth?rightDepth:leftDepth)+1;
    }
//迭代法(层序遍历+标记变量)
//只有当左右孩子都为空的时候才能说明遍历到最低点了,依旧采用层序遍历的方式,当到达最低点时,只需要通过标记变量退出即可。
public int minDepth(TreeNode root) {
        if(root==null) return 0;
        Queue<TreeNode> queue=new LinkedList<>();
        int depth=0;
        queue.offer(root);
        
        while(!queue.isEmpty()){
            int size=queue.size();
            depth++;
            boolean flag=false;            
            for(int i=0;i<size;i++){
                TreeNode node=queue.poll();
                if(node.left==null&&node.right==null){
                    flag=true;
                    break;
                }
                if(node.left!=null) queue.offer(node.left);
                if(node.right!=null) queue.offer(node.right);
            }
            if(flag) break;
        }
        return depth;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值