Leetcode_Minimum Depth of Binary Tree

题意为得出二叉树的最小深度,但深度是定义为从根节点到叶子节点的最少节点数。

容易出错的地方:为空节点时,直接返回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函数(即很长的那句代码,重复调用),导致超时。所以,写代码的时候,尤其要注意存储中间变量,避免没必要的多次函数调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值