104. Maximum Depth of Binary Tree
Asked at 18Microsoft51Apple49Bloomberg49Amazon45Google40Meta37LinkedIn66tcs27Yahoo100Arista Networks78Avito74Qualcomm58Spotify51Uber50Accenture44Zoho42Infosys39Oracle27
Problem
Return the maximum depth of a binary tree: the number of nodes on the longest path from the root down to a leaf.
Example: [3,9,20,null,null,15,7] → 3
depth(node) = 1 + max(depth(left), depth(right)), depth(None) = 0.
Complexity: O(n).
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))
assert Solution().maxDepth(make_tree([3, 9, 20, None, None, 15, 7])) == 3
assert Solution().maxDepth(None) == 0
class Solution {
public int maxDepth(TreeNode root) {
return root == null ? 0 : 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
return 1 + max(maxDepth(root.Left), maxDepth(root.Right))
}