一、问题描述
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.
二、思路
类似于Maximum Depth of Binary Tree,但注意一点,如果左子树或右子树,那么此时的二叉树的最小深度就必须从另外的子树中去求解,而不是像二叉树最大深度那道题。
三、代码
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
if(!root -> left) return 1 + minDepth(root->right);
if(!root -> right) return 1 + minDepth(root->left);
return min(minDepth(root -> left),minDepth(root ->right)) + 1;
}
};