原题: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 采用递归,判断当前节点是否为空,是空返回0
2 利用递归,返回左右节点较小的路径数+1
代码如下(错的):
class Solution {
public:
int minDepth(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(root==NULL) return 1;
else {
int left = minDepth(root->left);
int right = minDepth(root->right);
return left>right?right+1:left+1;
}
}
};
这个得到wrong answer。。。。非常郁闷,看了别人的代码,恍然大悟。。。。上述代码有这么个错误,当左右节点有一个为空时,可能有两种情况:
1 左右都为0,返回大子树和小子树的结果一样,都是0
2 有一个为空,一个不为空,即left*right==0,返回较大的那个子树的节点数,因为只有这一条路(另一个为空,路被截断)。。。。。
而1 2 可以用一个式子搞定,就是返回较大的那个子树的节点数。。。。
而上述就是求最大深度和最小深度的一个差别。。。
代码如下(60 ms):
class Solution {
public:
int minDepth(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(root==NULL) return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
if(left*right==0){
//左节点或右节点有一个不为空,说明该节点不为叶子。。。返回较大的(叶子节点的那个)
return left>right?left+1:right+1;
}
else{
//两个都不为空,返回较小的即可
return left>right?right+1:left+1;
}
}
};