Skip to content

104. Maximum Depth of Binary Tree 👍

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
class Solution {
 public:
  int maxDepth(TreeNode* root) {
    if (root == nullptr)
      return 0;
    return 1 + max(maxDepth(root->left), maxDepth(root->right));
  }
};
1
2
3
4
5
6
7
class Solution {
  public int maxDepth(TreeNode root) {
    if (root == null)
      return 0;
    return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
  }
}
1
2
3
4
5
class Solution:
  def maxDepth(self, root: TreeNode | None) -> int:
    if not root:
      return 0
    return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))