> 文章列表 > Leetcode.104 二叉树的最大深度

Leetcode.104 二叉树的最大深度

Leetcode.104 二叉树的最大深度

题目链接

Leetcode.104 二叉树的最大深度 easy

题目描述

给定一个二叉树,找出其最大深度

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

示例:

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

3
/ \\
9 20
/ \\
15 7

返回它的最大深度 3 。

解法:递归

我们要求一棵树的最大高度。

即,当前只有一个结点 1 + Max {左子树的最大高度 , 右子树的最大高度}

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

C++代码:

class Solution {
public:int maxDepth(TreeNode* root) {if(root == nullptr) return 0;int d = max(maxDepth(root->left) , maxDepth(root->right));return d + 1;}
};

Python代码:

class Solution:def maxDepth(self, root: Optional[TreeNode]) -> int:if root == None:return 0return max(self.maxDepth(root.left) , self.maxDepth(root.right)) +  1