Depth-First Search
Maximum Depth of Binary Tree
easy
DESCRIPTION (inspired by Leetcode.com)
Given the root of a binary tree, write a recursive function to find its maximum depth, where maximum depth is defined as the number of nodes along the longest path from the root node down to a leaf node.
Example 1:
Input:
[4, 2, 7, 1, null, 6, 9, null, 8, null, null, null, null, null, null]
Output: 4 (The 4 nodes along the longest path are shown in bold)
Code Editor
Python
Run your code to see results here
Have suggestions or found something wrong?
Explanation
We can solve this problem using the framework established in the Overview section.
Return Values
If I'm at a node in the tree, what values do I need from my left and right children to calculate the max depth of the current subtree?
- the maximum depth of the left subtree.
- the maximum depth of the right subtree.
This tells me that each recursive call should return the maximum depth of the subtree rooted at the current node.
So in the body of the recursive function, I'll make recursive calls to the current node's left and right children to get their max depths. Once I have those values, then the maximum depth of the subtree rooted at the current node is 1 (for the current node) + the maximum of the left and right depths. So, each node should return max(left, right) + 1 to its parent.
Base Case
The max depth of an empty tree is 0.
Helper Function
We don't need to pass values from the parent to the child to solve this problem, so we don't need to introduce a helper function.
Global Variables
Each recursive call returns the maximum depth of the subtree rooted at the current code, which matches the answer to the problem, so we don't need to use any global variables.
Solution
Solution
Python
class Solution:def maxDepth(self, root):if root is None:return 0# get the maximum depth of the left and right subtreesleft = self.maxDepth(root.left)right = self.maxDepth(root.right)return max(left, right) + 1
Animated Solution
Try these examples:
Visualization
Python
def maxDepth(root):if root is None:return 0left = maxDepth(root.left)right = maxDepth(root.right)return max(left, right) + 1
max depth of binary tree
0 / 29
What is the time complexity of this solution?
1
O(n)
2
O(x * y)
3
O(n * logn)
4
O(2ⁿ)
Mark as read