标签:
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.
Tree Depth-first Search
#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