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.
和求最大距离不一样,因为是求到叶子节点的最小距离,需要区分左右子树有可能为空的情况。
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL)
return 0;
if(root -> left == NULL && root -> right == NULL)
return 1;
if(root -> left != NULL && root -> right == NULL)
return minDepth(root -> left) + 1;
if(root -> left == NULL && root -> right != NULL)
return minDepth(root -> right) + 1;
return min(minDepth(root -> left) + 1,minDepth(root -> right) + 1);
}
};