Minimum Depth of Binary TreeTotal accepted:50435 Total submissions:173043my submissions QuestionSolution
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along, the shortest path from the root node to the nearest leaf node.
Hide TagsTree Depth-first SearchHas you met this question in a real interview? Yes No
Discuss
#include <iostream> #include <list>using namespace std; Definition for binary treestruct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode (int x): Val (x), left (null), right (null) {} };//is done using a queue method, a layer of search is made, and then the number of layers to search is recorded, and at that level, if there are any nodes that are//are not present in the tree and right subtree, Returns the number of layers directly, which is the resulting 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 trees (binary tree, queue)