Maximum Depth of Binary Tree — LeetCode 104 Python Solution
- Problem
- #104
- Pattern
- Tree Traversal
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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
- Input
- root = [3,9,20,null,null,15,7]
- Output
- 3
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: TreeNode) -> int:
if root is None:
return 0
l, r = self.maxDepth(root.left), self.maxDepth(root.right)
return 1 + max(l, r)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the number of nodes in the binary tree |
| Space | O(V) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 104. Maximum Depth of Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
On study lists
This problem is on Blind 75, NeetCode 150, Grind 75, LeetCode 75 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 104. Maximum Depth of Binary Tree?
- LeetCode 104. Maximum Depth of Binary Tree is rated Easy on LeetCode.
- What is the time complexity of LeetCode 104. Maximum Depth of Binary Tree?
- The Python solution on this page runs in O(n), where n is the number of nodes in the binary tree.
- What is the space complexity of LeetCode 104. Maximum Depth of Binary Tree?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 104. Maximum Depth of Binary Tree cover?
- LeetCode 104. Maximum Depth of Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.