简单易懂地求二叉树的最大深度

题目描述

在这里插入图片描述

我的解法

思路——迭代法

想要获得最大深度需要对真整个树进行遍历,而最大深度等于层数嘛,那使用层序遍历并在遍历过程中统计深度即可。但是深度优先的前、中、后遍历感觉处理起来反而很麻烦。

对应Java代码

在这里插入图片描述

class Solution {
    public int maxDepth(TreeNode root) {
        // 使用层序遍历,过程中的层数即为输出
        int maxDepth = 0;
        Deque<TreeNode> qu = new LinkedList<TreeNode>();
        if(root != null){qu.offerLast(root);}
        while(!qu.isEmpty()){
            maxDepth++;
            int levelSize = qu.size();
            for(int i = 0; i < levelSize; i++){
                TreeNode cur = qu.pollFirst();
                if(cur.left != null){qu.offerLast(cur.left);}
                if(cur.right != null){qu.offerLast(cur.right);}
            }
        }
        return maxDepth;
    }
}

复杂度分析

时间复杂度:O(n)
空间复杂度:O(n)

其他解法——递归法

此部分转载于公众号代码随想录

思路

左右要分开遍历,但是最大深度只能是其中一边的最大值,怎么解决递归过程中两边子树的重复叠加呢?即定义两个深度

  1. 确定参数和返回值
    返回值:这个树的深度
    参数:树的根节点
  2. 确定终止条件
    节点为空时,返回0
  3. 确定单层递归的逻辑
    先求它的左子树的深度,再求它的右子树的深度,最后取左右子树深度最大的数值+1

对应Java代码

在这里插入图片描述

class Solution {
    public int maxDepth(TreeNode root) {
        return getMaxDepth(root);
    }
    public int getMaxDepth(TreeNode node){
        if(node == null) {return 0;}
        int leftDepth = getMaxDepth(node.left);
        int rightDepth = getMaxDepth(node.right);
        int depth = 1 + Math.max(leftDepth,rightDepth);
        return depth;
    }
}

复杂度分析

时间复杂度:O(n)
空间复杂度:O(height) 其中height表示二叉树的高度,递归函数需要栈空间,而栈空间取决于递归的深度,因此空间复杂度等价于二叉树的高度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值