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.
S: Depth first search
int maxDepth(TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
111. Minimum Depth of Binary Tree
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
S: DFS
注意判断是否是leaf node以及root == NULL的特殊处理
int minDepth(TreeNode* root) {
if(!root) return 0;
if(!root->left && !root->right) return 1;
int left = root->left?minDepth(root->left): INT_MAX;
int right = root->right?minDepth(root->right): INT_MAX;
return min(left, right) + 1;
}