LeetCode Solutions
104. Maximum Depth of Binary Tree
Time: $O(n)$ Space: $O(1)$
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr)
return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
class Solution {
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.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))