剑指 Offer 55 – I. 二叉树的深度

本问题对应的 leetcode 原文链接:剑指 Offer 55 – I. 二叉树的深度
本问题配套打卡直达:【二叉树专题】剑指 Offer 55 – I. 二叉树的深度

问题描述

输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

例如:

给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

提示:

  1. 节点总数 <= 10000

解题思路

视频讲解直达: 本题视频讲解

代码实现

class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);

        return Math.max(left, right) + 1;
    }
}

发表回复

后才能评论

评论(2)

  • cute. 普通 2022年11月12日 上午9:46

    思路:递归

    var maxDepth = function(root) {
        if (root == null) return 0;
        let left = maxDepth(root.left);
        let right = maxDepth(root.right);
        return Math.max(left, right) + 1;
    };
    

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

  • 优秀市民 普通 2022年10月27日 下午11:18
    class Solution {
        public int maxDepth(TreeNode root) {
            if(root == null) {
                return 0;
            }
            return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
    
        }
    }
    

    时间复杂度o(n)
    空间复杂度o(n)