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.
解题思路:采用递归的方法来解决这个问题,其实递归可以解决的问题都可以通过非递归来解决,刷第二遍的时候再采用非递归的方式来解决这些问题。
其实与求二叉树的深度的思路差不多,唯一的区别是针对左右子树为空的时候的情景了。
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
int minDepth(TreeNode* root)
{
if(!root)
{
return 0;
}
int lmin=minDepth(root->left);
int rmin=minDepth(root->right);
if(lmin==0&&rmin==0)
{
return 1;
}
if(lmin==0)
{
lmin=INT_MAX;
}
if(rmin==0)
{
rmin=INT_MAX;
}
return min(rmin,lmin)+1;
}
};