[牛客网 -leetcode在线编程 -02] minimum-depth-of-binary-tree -树的最短深度

题目描述

题目描述
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.

代码及思路注释

#include <bits/stdc++.h>
#include <iostream>
using namespace std;
/*
大致题意: 求二叉树的最短树的深度,从root结点到叶子结点的最短路  
*/ 
struct TreeNode{
	TreeNode * left;
	TreeNode * right;
};
class Solution {
public:
    int run(TreeNode *root) {
    	//1.空树 
    	if(!root){
    		return 0;
		} 
		queue<TreeNode *> Q;
		
		//进行层次(广度)遍历
		Q.push(root);
		int level=1;
		int now=1;
		int cnt=1;
		 
		while(Q.size()>0){
			cnt=now;
			now=0;
			
			//如下遍历cnt个节点, 将cnt个结点全部遍历查找 
			while(cnt--){
				//取出queue第一个结点 
				TreeNode * t=Q.front();
				Q.pop();
				
				if(!t->left&&!t->right) 
					return level;
					
				if(t->left){
					Q.push(t->left);
					now++; 
				} 	
				if(t->right){
					now++;
					Q.push(t->right);
				}
					
			}
				
			level++;
		}
		 
    	return 9999;
    }
};

int main(int argc, char** argv) {

	return 0;
}

/*
ctrl+E: 复制当前行
ctrl+D: 删除当前行
 
*/
原文地址:https://www.cnblogs.com/zhazhaacmer/p/10567814.html