Maximum Depth of Binary Tree
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.
The maximum depth of the binary tree in the above image is 3.
Solution
Use a recursive function to calculate the maximum depth of the tree. The function will return the maximum depth of the left and right child nodes, and then return the maximum of the two plus one.
Implementation
Pseudocode
- If the root is
None
, return 0. - Return the maximum of the maximum depth of the left and right child nodes plus one.
Complexity Analysis
- Time Complexity:
O(n)
- because we visit each node exactly once. - Space Complexity:
O(n)
- in the worst case, the space complexity isO(n)
due to the recursive call stack.