题目描述
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:
//find the minimum depth
int run(TreeNode *root) {
int left=0;
int right=0;
if(root==NULL) return 0;
if(root->left==NULL&&root->right==NULL) return 1;
left=run(root->left);
right=run(root->right);
if(left==0&&right!=0) return right+1;//左子树为空而右子数不为空
if(left!=0&&right==0) return left+1;//右字树为空而左字数不为空
return left>right?right+1:left+1;//返回左右字树中高度较小的
}
};