BM28. [二叉树的最大深度]

alt

https://www.nowcoder.com/exam/oj?tab=%E7%AE%97%E6%B3%95%E7%AF%87&topicId=295

BM28. 二叉树的最大深度

题目分析

求二叉树的最大深度,不就是从下向上求层数吗?所以二叉树的最大深度不就是后序遍历吗?

  1. 先求左右子树的深度
  2. 那个深度更深保留哪一个作为深度
  3. 然后向上处理

完整代码

 private int maxDepth(TreeNode root) {
        if (root == null)
            return 0;
        int l= maxDepth(root.left);
        int r=maxDepth(root.right);
        // 后序遍历来了
        int max = Math.max(l, r) + 1;
      return max;
    }
  • 时间复杂度:,后续遍历二叉树
  • 空间复杂度:,没有使用额外的空间

alt

#面经##题解##面试题目#
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务