您的位置:首页 > 其它

Leetcode_Minimum Depth of Binary Tree

2015-02-09 10:37 337 查看
题意为得出二叉树的最小深度,但深度是定义为从根节点到叶子节点的最少节点数。

容易出错的地方:为空节点时,直接返回0。这是不对的,要判断其是否有兄弟节点,没有兄弟节点的时候才能返回0,即这个节点的父节点是一个叶子节点。

错解1:

class Solution {
public:
int minDepth(TreeNode *root) {
if(root==nullptr)
return 0;
return 1+min(minDepth(root->left),minDepth(root->right));

}
};

错解2:
class Solution {
public:
int minDepth(TreeNode *root) {
if(root==nullptr)
return 0;
if(root->left ==nullptr&&root->right==nullptr)
return 1;

return 1+(min(minDepth(root->left),minDepth(root->right))==0?max(minDepth(root->left),minDepth(root->right)):min(minDepth(root->left),minDepth(root->right)));

}
};<span style="color: rgb(169, 68, 66); font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 18px; line-height: 19px; background-color: rgb(253, 253, 253);">Time Limit Exceeded</span>

正解:
class Solution {
public:
int minDepth(TreeNode *root) {
if(root==nullptr)
return 0;
if(root->left ==nullptr&&root->right==nullptr)
return 1;

int lLen=minDepth(root->left);
int rLen=minDepth(root->right);
if(lLen&&rLen)//判断最小的那个是不是为0,为0的话,则是空节点,要以另一个节点的深度为准
return 1+min(lLen,rLen);
else
{
return 1+max(lLen,rLen);
}
}
};错解2和正解,其实思路是一样的。但是错解2,由于没有设置中间变量,导致多次调用minDepth函数(即很长的那句代码,重复调用),导致超时。所以,写代码的时候,尤其要注意存储中间变量,避免没必要的多次函数调用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息