题目描述:
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.
思路:
用递归的思想:
如果根结点为空,就返回0;
如果左子树为空,就返回右子树的最小深度+1(算上根结点这一层)
如果右子树为空,就返回左子树的最小深度+1
如果左、右子树都不为空,则返回左、右子树最小深度+1
class solution{
public:
int run(TreeNode *pRoot)
{
if(pRoot == NULL){ //根结点为空,返回0值
return 0;
}
if(pRoot->pLeft == NULL){ //左子树为空,返回右子树的最小深度+1;
return run(pRoot->Pright)+1;
}
if(pRoot->pright == NULL){ //右子树为空,返回左子树的最小深度+1;
return run(pRoot->pLeft);
}
//左右子树都不为空,返回左右子树中的最小深度+1
int LeftDepth = run(pRoot->pLeft)+1;
int RightDepth = run(pRoot->pRight)+1;
return (LeftDepth < RightDepth)?(LeftDepth+1):(RightDepth+1);
}
};