Maximum Depth of Binary Tree
Examples
Example 1:
Input: root = [1, 2, 3, null, null, 4]
Output: 3
Example 2:
Input: root = []
Output: 0
Example 1:
Input: root = [1, 2, 3, null, null, 4]
Output: 3
Example 2:
Input: root = []
Output: 0
Given the root of a binary tree, return its depth.\n\nThe depth of a binary tree is defined as the number of nodes along the longest path from the root node down to the farthest leaf node.
0 <= The number of nodes in the tree <= 100-100 <= Node.val <= 100Use DFS recursion. The depth of a node is 1 + max(depth(left), depth(right)). For a null node, return 0. This handles empty trees and skewed trees directly.
Every path from the root to a leaf must pass through one child at each step. Taking the maximum depth of the two subtrees yields the longest such path. The recursion computes this exactly for every node.
O(n)O(h) where h is tree heightclass Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))