104. Maximum Depth of Binary Tree
1. Description
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
2. Note
- A leaf is a node with no children.
3. Example
Example 1:
Given binary tree [3,9,20,null,null,15,7],
return its depth = 3.
4. Constraints
- The number of nodes in the tree is in the range [0, $10^4$].
- -100 <= Node.val <= 100
4. Solutions
Recursive
n is the number of nodes in i_root
Time complexity: O(n)
Space complexity: O(n)
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) {
return 0;
} else {
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
}
};