您的位置:首页 > 其它

Minimum Depth of Binary Tree--LeetCode

2015-04-05 10:30 218 查看

题目:

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.

思路:这里递归就需要注意一些东西了,对于非递归来说,只要发现有一个节点没有左子树同时也没有右子树,那么这个就是节点所在层次就是目标

int MinDepth(BinTree* root)
{
	if(root == NULL)
		return 0;
	if(root->left == NULL)
		return MinDepth(root->right)+1;
	if(root->right == NULL)
		return MinDepth(root->left)+1;
	return min(MinDepth(root->left),MinDepth(root->right))+1;
}

int MinDepth_second(BinTree* root)
{
	if(root == NULL)
		return 0;
	BinTree* node;
	deque<BinTree*> de;
	int num;
	int curnum=0;
	int level=0;
	de.push_back(root);
	num=1;
	while(!de.empty()) 
	{
		node = de.front();
		de.pop_front();
		num--;
		if(node->left==NULL && node->right == NULL)
			return level+1;
		if(node->left != NULL)
		{
			de.push_back(node->left);
			curnum++;
		}
			
		if(node->right !=NULL)
		{
			de.push_back(node->right);
			curnum++;
		}	
		if(num == 0)
		{
			num = curnum;
			curnum=0;
			level++;
		}
		
	}
	
	return level;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: