55-I. 二叉树的深度

1. 描述

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

2. 例子

示例 1:
给定二叉树 [3,9,20,null,null,15,7],
返回它的最大深度 3 。

3. 限制

  • 节点总数 <= 10000

4. 题解

n 是 i_root 中的节点个数
时间复杂度: O(n)
空间复杂度: O(n)

class Solution 
{
public:
    // int maxDepth(TreeNode* root) 
    int maxDepth(TreeNode *i_root) 
    {
        if(!i_root) return 0;
        
        return 1 + max(maxDepth(i_root->left), maxDepth(i_root->right));
    }
};
comments powered by Disqus