【问题描述】:
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.
给定一个二叉树,求出它的最小深度,最小深度是从根节点到最近的叶子节点的最短路径的节点数。
解题思路:
以下图为例:1:我们首先判断是否是空树的情况,很显然这个不是,根节点不为空;
2:然后我们判断是不是左右子树都没有;
3:然后我们判断没有左子树,有右子树的情况,然后递归,以此时的右子树为根节点,从上到下继续1,2,3操作;
4:然后我们判断没有右子树,有左子树的情况,然后递归,以此时的左子树为根节点,从上到下继续1,2,3,4操作;
5:最后左右子树都有,我们将左右子树看成新的树,继续1,2,3,4,5的操作;
下面是我在牛客网oj环境下编译的,成功通过所有测试:
class Solution {
public:
int run(TreeNode *root) {
if(root==NULL)//根节点为空,即树为空
return 0;
if((root->left==NULL)&&(root->right==NULL))//没有左右树
return 1;
if(root->left==NULL)//没有左子树,以右子树为根,看它的左右子树
{
return run(root->right)+1; //子问题,继续递归
}else if(root->right==NULL)//同上
{
return run(root->left)+1;
}else {
return (run(root->right)<run(root->left)?run(root->right)+1:run(root->left)+1);
}
}
};