首页 > 其他 > 详细

Leetcode_Minimum Depth of Binary Tree

时间:2015-02-09 12:56:37      阅读:263      评论:0      收藏:0      [点我收藏+]

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

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

Leetcode_Minimum Depth of Binary Tree

原文:http://blog.csdn.net/yinqiaohua/article/details/43668167

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!