这道题非常简单:
LeetCode 104: Maximum Depth of Binary Tree
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.
通过代码:
// C
int maxDepth(struct TreeNode* root) {
if(!root) return 0;
int l = maxDepth(root->left);
int r = maxDepth(root->right);
return 1 + (l > r ? l : r);
}
// C++
int maxDepth(struct TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}