Intuition
- On each subroutine, return 1 + the max of any of the two branches.
Complexity
Runtime
since you traverse through every node once.
Space
since the height of a binary tree can be N nodes long, meaning N nodes of stack space, with space in the case of a balanced tree, since there are nodes on every level. (n / 2 / 2 / 2 …) until = 1.
Code
# 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: Optional[TreeNode]) -> int:
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))