[LeetCode]#104. Maximum Depth of Binary Tree
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:
- If root is None, return 0.
- If roo.left and root.right are None, return 1.
- 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