[LeetCode]#104. Maximum Depth of Binary Tree

Fatboy Slim
Jan 20, 2021

Environment: Python 3.8

Key technique: TreeNode

Given the root of a binary tree, return its maximum depth.

A binary tree’s maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 3

Analysis:

  1. If root is None, return 0.
  2. If roo.left and root.right are None, return 1.
  3. Calculate 1+max (root.left maxdepth , root.right maxdepth)

Solution:

class Solution:
def maxDepth(self, root):
if root is None:
return 0
if root.left is None and root.right is None:
return 1
ans= 1 + max(self.maxDepth(root.left),self.maxDepth(root.right))
return ans

Submissions:

Reference:

https://leetcode.com/problems/maximum-depth-of-binary-tree/discuss/1022054/Easy-python-solution

--

--