码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_111题——Minimum Depth of Binary Tree(二叉树,队列)

时间:2015-04-16 12:10:14      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

Minimum Depth of Binary Tree

 Total Accepted: 50435 Total Submissions: 173043My Submissions

 

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.

 

Hide Tags
 Tree Depth-first Search
Have you met this question in a real interview? 
Yes
 
No
 

Discuss

#include<iostream>
#include<list>
using namespace std;

 //Definition for binary tree
struct TreeNode {
      int val;
      TreeNode *left;
      TreeNode *right;
      TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  };

//用队列的方法来做,一层层的进行搜索,然后记录下搜索的层数,在那一层如果出现左子树和右子树都
//没有的结点,则直接返回层数,即为所求结果
int minDepth(TreeNode *root) {
        if(root==NULL)
			return 0;
		list<TreeNode*> temp;
		temp.push_back(root);
        int min_depth=1;
		int row_size=1;
		TreeNode* temp_node;

		while(!temp.empty())
		{
			while(row_size--)
			{
				temp_node=temp.front();
				temp.pop_front();
				if(temp_node->left==NULL&&temp_node->right==NULL)
					return min_depth;
				if(temp_node->left!=NULL)
					temp.push_back(temp_node->left);
				if(temp_node->right!=NULL)
					temp.push_back(temp_node->right);
			}
			row_size=temp.size();
			min_depth++;	
		}
    }

int main()
{

}

  

leetcode_111题——Minimum Depth of Binary Tree(二叉树,队列)

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4431245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!