Maximum Depth of a Binary Tree
DESCRIPTION (credit 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.
EXAMPLES
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)
Run your code to see results here
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
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
def maxDepth(root):if root is None:return 0left = maxDepth(root.left)right = maxDepth(root.right)return max(left, right) + 1
Complexity Analysis
Time Complexity: O(N), where N is the number of nodes in the tree. We visit each node exactly once, and at each node, we perform constant time work. Space Complexity: O(N), where N is the number of nodes. A total of N call frames have to be allocated, one for each node in the tree.
Loading comments...